作者:HS_G_960 | 来源:互联网 | 2023-10-11 18:29
freemarker基本指令用法
1、if指令
[#if 条件]
...
[/#if]
[#if 条件]...[#else]...
[/#if][#if 条件]...[#elseif 条件]...[#else]...
[/#if]
2、list指令
[#list animals as animal] ...
[/#list]
[#list animals] ...[#items as animal] ...[/#items]
[/#list]
[#list animals as animal] $ {animal}[#sep],[/#sep]
[/#list]
[#list animals as animal]${animal}[#sep],[/#sep][#else]None
[/#list]
[#list animals ]...[#items as animal]${animal}[#sep] ...[/#sep][/#items]
[#else]
...
[/#list]
3、include指令
使用该include指令,您可以将另一个文件的内容插入到模板中。
[#include "/copyright_footer.html"]
4、使用内置插件
FreeMarker使用?启动调用内置插件
${user?upper_case} ${user?cap_first} ${user?length} ${animal.protected?string("Y", "N")} ${user?starts_with("J")} ${1.1?int} ${animals?size} ${fruits?join(", ")} [#list animals as animal]${animal?index} ${animal?counter} ${animal?item_parity} [/#list]
内置插件是可以连接一起使用,例如:
${fruits?join(", ")?upper_case}
${1.1?int} //取整
5、处理缺失的变量
所谓缺失值的意思是:在FreeMarker的模型中不存在的变量,处理方式有两种:
- 设置默认值,关键符 !
${user! "visitor" }
备注:如果给一个对象的某个属性设置默认值应该 ${(user.name)!""},如果不加括号,那么如果user也是缺失值,那么FreeMarker会报错。
- 使用if判断是否是缺失变量,关键符号两个文号 ??
[#if user??]
[/#if]
6、“. .”操作符
“…”用来表示一个范围,通常用于截取字符串和序列
start..end 包含开始和结束。例:0..5 相当于[0,5]
start..<end 和 start..!end 包含开始但不包含结束。例&#xff1a; 0..<5 相当于[0,)
start..*length 长度限制范围。例&#xff1a; 1..*5 相当于 1 2 3 4 5
start.. 右无界范围。这就像长度有限的范围&#xff0c;长度无限。例如&#xff0c;1.. 相当于 [1, 2, 3, 4, 5, 6, ... ]无限
“. .”操作符并不真正存储它们所包含的数字&#xff0c;因此例如0. .1并且 0. .100000000速度相同&#xff0c;占用的内存也相同。
该操作符可用于字符串操作和序列操作。例如&#xff1a;
${name[0..5]}
${name[0..<5]}
${name[0..*5]}
${name[5..]}
[#list animals[0..5] as animal] ${animal.name} [/#list]
[#list animals[0..<5] as animal] ${animal.name} [/#list]
[#list animals[0..*5] as animal] ${animal.name} [/#list]
[#list animals[5..] as animal] ${animal.name} [/#list]
[#list animals[10..5] as animal] ${animal.name} [/#list]
[#list 0..10 as num] ${num} [/#list]
7、r转义
如果你想直接在页面上显示“${name}”字符串就得使用r进行转义。例如
${r"${name}"}
8、assign关键字
assign用于自定义变量
例如&#xff1a;
[#assign name&#61;"freemarker"]
[#assign name&#61;"Hello ${user} !"]
[#assign name&#61;"free" &#43; “marker”]
<#assign seq1 &#61; ["abc"&#xff0c;"bcd"&#xff0c;"cde"]>
<#assign seq2 &#61; seq1 &#43; ["efg"]>
<#assign seq3 &#61; ["a"&#xff0c;["b","c"]&#xff0c;"d"]>
<#assign ages &#61; {"Joe"&#xff1a;23&#xff0c;"Fred"”&#xff1a;25}>
<#assign ages &#61; {"Joe"&#xff1a;23&#xff0c;"Fred"&#xff1a;25} &#43; {"Joe"&#xff1a;30&#xff0c;"Fred"&#xff1a;18}>
<#assign num &#61; 25>
<#assign num &#61; 25 &#43; 10 * 12>
更多用法参考&#xff1a;FreeMarker官方文档