importfreemarker.template.*;importjava.util.*;importjava.io.*;publicclassTest{publicstaticvoidmain(String[]args)throwsException{/* ------------------------------------------------------------------------ *//* You should do this ONLY ONCE in the whole application life-cycle: *//* Create and adjust the configuration singleton */Configurationcfg=newConfiguration(Configuration.VERSION_2_3_32);cfg.setDirectoryForTemplateLoading(newFile("/where/you/store/templates"));// Recommended settings for new projects:cfg.setDefaultEncoding("UTF-8");cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);cfg.setLogTemplateExceptions(false);cfg.setWrapUncheckedExceptions(true);cfg.setFallbackOnNullLoopVariable(false);cfg.setSQLDateAndTimeTimeZone(TimeZone.getDefault());/* ------------------------------------------------------------------------ *//* You usually do these for MULTIPLE TIMES in the application life-cycle: *//* Create a data-model */Maproot=newHashMap();root.put("user","Big Joe");Productlatest=newProduct();latest.setUrl("products/greenmouse.html");latest.setName("green mouse");root.put("latestProduct",latest);/* Get the template (uses cache internally) */Templatetemp=cfg.getTemplate("test.ftlh");/* Merge data-model with template */Writerout=newOutputStreamWriter(System.out);temp.process(root,out);// Note: Depending on what `out` is, you may need to call `out.close()`.// This is usually the case for file output, but not for servlet output.}}
/**
* Product bean; note that it must be a public class!
*/publicclassProduct{privateStringurl;privateStringname;// As per the JavaBeans spec., this defines the "url" bean property// It must be public!publicStringgetUrl(){returnurl;}publicvoidsetUrl(Stringurl){this.url=url;}// As per the JavaBean spec., this defines the "name" bean property// It must be public!publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}}
FTL 标签与 HTML 标签一样,必须正确嵌套。所以下面的代码是错误的,因为 if 指令既在 list 指令的嵌套内容的内部又在外部:
1
2
3
4
5
6
7
8
<ul><#list animals as animal>
<li>${animal.name} for ${animal.price} Euros
<#if user == "Big Joe">
(except for you)
</#list> <#-- WRONG! The "if" has to be closed first. -->
</#if>
</ul>