不做浮躁的人
正在行走的人...
posts - 171,  comments - 51,  trackbacks - 0

1、配置对象:
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));
cfg.setObjectWrapper(new DefaultObjectWrapper()); 


2:得到模板对象:
Template temp = cfg.getTemplate("test.ftl"); 
Configuration对Template对象进行缓存。

3:合并模板和数据模型:
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
out.flush(); 


4:数据模型:
      任何模板要使用的数据模型都是通过object wrapping将传入的对象包装成实现TemplateModel接口的对象。
      TemplateModel提供几个下级接口:TemplateSequenceModel等。

5:单值模型:Scalars   
      Boolean 
      Number 
      String 
      Date

  Template Type Model
6:方法    
public class IndexOfMethod implements TemplateMethodModel {
   
    public TemplateModel exec(List args) throws TemplateModelException {
        if (args.size() != 2) {
            throw new TemplateModelException("Wrong arguments");
        }
        return new SimpleNumber(
            ((String) args.get(1)).indexOf((String) args.get(0)));
    }

root.put("indexOf", new IndexOfMethod()); 

<#assign x = "something">
${indexOf("met", x)}
${indexOf("foo", x)} 

7:Transforms
   import java.io.*;
import java.util.*;
import freemarker.template.TemplateTransformModel;

class UpperCaseTransform implements TemplateTransformModel {

    public Writer getWriter(Writer out, Map args) {
        return new UpperCaseWriter(out);
    }

    private class UpperCaseWriter extends Writer {
      
        private Writer out;
          
        UpperCaseWriter (Writer out) {
            this.out = out;
        }

        public void write(char[] cbuf, int off, int len)
                throws IOException {
            out.write(new String(cbuf, off, len).toUpperCase());
        }

        public void flush() throws IOException {
            out.flush();
        }

        public void close() {
        }
    }
}

root.put("upperCase", new UpperCaseTransform());

<@upperCase>
blah2
blah3
</@upperCase>

8:访问freemarker的环境变量:Environment.getCurrentEnvironment()

9:共享变量是指所有模板都能访问的变量,在configuration中设置。
      cfg.setSharedVariable("to_upper", new UpperCaseTransform());
      cfg.setSharedVariable("company", "Foo Inc.");      

      数据模型中的变量将会隐藏同名的共享变量。

      TemplateModel的实现不是线层安全的,因此不能用于共享变量。

      预置共享变量:
      

name

class

capture_output

freemarker.template.utility.CaptureOutput

compress

freemarker.template.utility.StandardCompress

html_escape

freemarker.template.utility.HtmlEscape

normalize_newlines

freemarker.template.utility.NormalizeNewlines

xml_escape

freemarker.template.utility.XmlEscape

 
10:设置层次:configuration, template, runtime environment

    
posted on 2007-03-25 21:38 不做浮躁的人 阅读(1108) 评论(0)  编辑  收藏 所属分类: freemarker

只有注册用户登录后才能发表评论。


网站导航:
 

<2007年3月>
25262728123
45678910
11121314151617
18192021222324
25262728293031
1234567

常用链接

留言簿(9)

随笔分类(31)

随笔档案(75)

文章分类(1)

文章档案(3)

搜索

  •  

最新评论

阅读排行榜

评论排行榜