模板引擎:根据模板与绑定的数据,生成最终的xml文本。
java领域的表现层的三大模板引擎——jsp,velocity,freemarker。jsp,java server page。
官网:http://freemarker.org/
1.依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
2.模板组成部分
文本:直接输出的部分注释:<#-- content -->数据模型:${data.field}
3.相关类
freemarker.template.Configuration 配置类。 freemarker.template.Configuration.Configuration(Version incompatibleImprovements) 构造函数。 void freemarker.template.Configuration.setDirectoryForTemplateLoading(File dir) 设置存放模板文件(若干个 xx.ftl)的目录。 void freemarker.template.Configuration.setDefaultEncoding(String encoding) 设置编码格式。 Template freemarker.template.Configuration.getTemplate(String name) 根据文件名拿到template。 void freemarker.template.Template.process(Object dataModel, Writer out) 有了模板与数据,得到输出,写入out中。若想得到字符串,一般会传入StringWriter。
4.常用指令
list
for循环遍历的效果。
<#list fruits as fruit><br> <li>${fruit.name}<br> </#list>
if
条件判断。为真时,标签对内的内容才会输出。
<#--标签内的属性,不能用${}的形式-->
<#if isBig && isExpensive>Wow!</#if>
<#-- 使用关系比较符时,可以直接用大于号,但要放在括号内,保证标签闭合符号能被正确处理-->
<#if (x>y)>x is larger than y</#if>
<#-- 使用关系比较符时,也可以用-->
<#if (x gt y)>x is larger than y</#if>
??
判断某个变量是否存在
var?length
取得字符串长度
var?c
将数字转为字符串
assign
引入局部变量并赋值
5.例子
6.常见错误
当用到了${object.x},但datamodel中没有这个属性,就会报下面这样的错误。
Error executing FreeMarker template
FreeMarker template error:
The following has evaluated to null or missing:解决办法:使用<#if obj.x??>做判断。
相关资源:python入门教程(PDF版)