assign指令
使用该指令你可以创建一个新的变量, 或者替换一个已经存在的变量。
- 定义简单类型
<#assign linkman="张小姐">
联系人:${linkman}
- 定义对象类型
<#assign info={"mobile":"12345678911","address":"广东深圳"}>
电话:${info.mobile} 地址:${info.address}
include指令
你可以使用它在你的模板中插入另外一个 FreeMarker 模板文件 (由 path 参数指定)。 被包含模板的输出格式是在 include 标签出现的位置插入的。 被包含的文件和包含它的模板共享变量,就像是被复制粘贴进去的一样。
这个指令不能和JSP(Servlet)的include搞混, 因为它不涉及到Servlet容器中,只是处理应外一个FreeMarker模板, 不能"离开"FreeMarker。
创建模板文件head.ftl
<h1>官方网站</h1>
在模板文件test2.ftl中使用include指令引入模板head.ftl
<body>
<#--include指令-->
<#include "head.ftl">
<#--通常使用 /(斜杠)来分隔路径成分, 而不是 \(反斜杠)。如果你从你本地的文件系统加载模板, 而它使用反斜杠(像Windows操作系统),也要使用 /。-->
<#--我是一个注释,不会输出-->
<!--html注释-->
<#--assign指令:定义对象类型-->
<#assign info={"mobile":"12345678911","address":"广东深圳"}>
电话:${info.mobile} 地址:${info.address}
<br>
</body>
if, else, elseif 指令
在代码中对变量x赋值
Map map=new HashMap();
map.put("x", 3);
在模板文件上添加
<body>
<#-- if, else, elseif 指令指令 -->
<#--freemarker中“=”与“==”是一个意思-->
<#if x == 1>
x is 1
<#elseif x == 2>
x is 2
<#elseif x == 3>
x is 3
<#elseif x == 4>
x is 4
<#else>
x is not 1 nor 2 nor 3 nor 4
</#if>
<br/>
</body>
list指令
代码中对变量goodsList赋值
Map map=new HashMap();
List goodsList=new ArrayList();
Map goods1=new HashMap();
goods1.put("name", "苹果");
goods1.put("price", 5.8);
Map goods2=new HashMap();
goods2.put("name", "香蕉");
goods2.put("price", 2.5);
Map goods3=new HashMap();
goods3.put("name", "橘子");
goods3.put("price", 3.2);
goodsList.add(goods1);
goodsList.add(goods2);
goodsList.add(goods3);
map.put("goodsList", goodsList);
在模板文件上添加
<body>
--------商品价格表--------<br>
<#list goodsList as goods>
<#--如果想在循环中得到索引,使用循环变量+_index就可以得到。-->
${goods_index+1} 商品名称: ${goods.name} 价格:${goods.price}<br>
</#list>
</body>