为使用Freemarker模板时的关键性语法编写代码示例或说明,主要用于回忆性检索或速查,阅读需要一定代码基础或对Freemarker有了解。
常用Freemarker语法简例
常用Freemarker语法简例(二)
bool值
<#-- 输出 true: -->
${foo?c}
<#assign foo = true>
<#-- 输出 Y: -->
${foo?then('Y', 'N')}
<#assign foo = false>
<#-- 输出 N: -->
${foo?then('Y', 'N')}
<#assign x = 10>
<#assign y = 20>
<#-- 输出x、y中较大的: -->
${(x > y)?then(x, y)}
数字类型
<#assign a = 2378492>
${a} -- 2,378,492
${a?c} -- 2378492
<#assign a =2.79>
?floor=${a?floor} -- 2
?ceiling=${a?ceiling} -- 3
?round=${a?round} -- 3
?round=${a?is_nan} -- false
?round=${a?is_infinite} -- false
字符串处理
${string?html} html encode处理
${string?length} 字符串长度
${string?replace(a,b)} 替换a为b
${string?js_string} 转义' "
${string?url} 进行url转义处理
${string?url_path} 进行url转义处理,但是不转义 /
...
列表处理
<#assign colors = ["red", "green", "blue"]>
${colors?size} 元素数量
${colors?first} 获取第一个元素
${colors?last} 获取最后一个元素
${colors?join(", ")} 使用,连接数组元素
${colors?sort} 以升序排列,支持简单数据类型,不支持对象
对象类型,需使用特定属性排序
${objects?sort_by("weight")} 可按照特定属性排序
${objects?sort_by(['name', 'last'])} 可处理数据结构层级比较深的情况 如 object.name object.item.user.last 等
哈希表处理
<#assign h = {"name":"mouse", "price":50}>
<#assign keys = h?keys>
<#list keys as key>${key} = ${h[key]}; </#list>
时间格式化
对于时间格式的变量,必须进行格式转化
- ?time 仅显示时间部分
- ?date 仅显示日期部分
- ?datetime 包括日期和时间
- ?string[“yyyy-MM-dd HH:mm”]
<#assign openingTime = .now>
${openingTime?time} <#-- ?time等参数为必须的参数,否则将失败 0-->
或:
<#assign openingTime = openingTime?time>
${openingTime}
其他 string
的时间处理函数
${openingTime ?string.short}
${openingTime ?string.medium}
${openingTime ?string.long}
${openingTime ?string.full}
${openingTime ?string.medium_short} <#-- medium date, short time -->
${openingTime ?string.xs}
${openingTime ?string.iso}
---
输出:
string.short:2/20/07 01:45 PM
string.medium: Feb 20, 2007 01:45:09 PM
string.long:February 20, 2007 01:45:09 PM PST
string.full:Friday, February 20, 2007 01:45:09 PM PST
string.medium_short: Feb 8, 2003 9:24 PM
string.xs: 2007-02-20T13:45:09-08:00
string.iso: 2007-02-20T13:45:09-08:00
时间格式化:
${lastUpdated?string["EEEE, MMMM dd, yyyy, hh:mm a '('zzz')' "]}
${lastUpdated?string["EEE, MMM d, ''yy"]}
${lastUpdated?string.yyyy} <#-- 与 ${lastUpdated?string["yyyy"]} 相同 -->
---
输出:
Tuesday, April 08, 2003, 09:24 PM (PDT)
Tue, Apr 8, '03
2003
${lastUpdated?string.iso_m_u}
${lastUpdated?string.xs_ms_nz}
---
输出:
2007-02-20T21:45Z
2007-02-20T13:45:09.000