Freemarker对于多风格的应用

来源:互联网 发布:香港购物 知乎 编辑:程序博客网 时间:2024/05/21 08:47

论坛产品或者博客产品大多都支持多套模板,用户可以进行随意切换来体验各种风格。OSPod.Forum 提供了截然不同的两套用户体验风格,在不同的模板之间需要有一些公用的地方,或者通过扩展其中一套模板或者进行微调之后达到一种新的风格,如基于蓝色模板修改成为黑色比较酷的风格等等?如何保障部分模板之间的复用呢?

freemarker.template.Configuration给我们提供了模板装载机制的修改方案,通过config.setTemplateLoader(TemplateLoaderImp) ,我们可以告诉Freemarker使用哪个模板装载类,OK,这样需要实现我们自己的模板转载类。

OSPod.Forum通过扩展TemplateLoader来提供模板装载机制,该类的基础原型是基于ServletContextTemplateLoader来进行实现,在该类基础上覆盖findTemplateSource方法实现,参考如下:

public Object findTemplateSource(String name) throws IOException {
      String fullPath 
= path + name;
      
// First try to open as plain file (to bypass servlet container resource caches).
      try {
          String realPath 
= servletContext.getRealPath(fullPath);
          
if (realPath != null{
              File file 
= new File(realPath);
              
if(!file.isFile()) {  //如果找不到模板
                  String tplStyle = (String)ActionContext.getContext().getAttributeMap().get( "_tplStyle" );
                  
if(!Checker.isEmpty( tplStyle )){
                                          
//替换模板寻找路径
                      String refStyle = GeneralConfigRepository.getTemplateExtendFrom(tplStyle);
                      realPath 
= realPath.replaceAll( tplStyle, refStyle );
                      file 
= new File(realPath);
                      
if(!file.isFile())
                       
return null;
                  }
else{
                      
return null;
                  }

              }

              
if(file.canRead()) {                    
                  
return file;
              }

          }

      }
 catch (SecurityException e) {
          logger.error( 
"获得模版" + fullPath + "错误!", e );
      }

      
          
      
// If it fails, try to open it with servletContext.getResource.
      URL url = null;
      
try {
          url 
= servletContext.getResource(fullPath);
      }
 catch(MalformedURLException e) {
          logger.warn(
"Could not retrieve resource " + fullPath, e);
          
return null;
      }

      
return url == null ? null : new URLTemplateSource(url);
  }