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
不做浮躁的人 閱讀(1125)
評論(0) 編輯 收藏 所屬分類:
freemarker