Freemarker tips

[size=small][b][color=blue]三目运算 –条件运算符[/color][/b]
用freemarker时写三目运算,开始一直这样写,${true?3:4}, 不行,再换成: ${true?'3':'4'},汗,还是不行,然后想起freemarker输出字符串后面要带上?string,
所以又写上${true?'3'string:'4'string},汗,一样不行,最后问以前的同事(大名高登峰,未婚,嘎嘎),原来是这样写:
Java代码
1. ${true?string('5','7')}


[b][color=blue]Check null[/color][/b]
<#if updatedTaxonomyItems??>
Do something if not null
</#if>
<#else>
Do something if null
</#else>

[b][color=blue]Use Default value if null[/color][/b]
${updatedItem.parentNodeId!"NULL"}

[b][color=blue]关于得到list长度的问题[/color][/b]
取得list的长度:${fields?size}。

而使用判断其长度的时候,

<#if fields?size>0 >
</#if>

竟抛出错了,说不是boolean类型,

Java backtrace for programmers:
----------
freemarker.core.NonBooleanException: Error on line 132, column 22 in viewEntity_js.ftl
Expecting a boolean (true/false) expression here
Expression fields?size does not evaluate to true/false
it is an instance of freemarker.template.SimpleNumber
at freemarker.core.Expression.isTrue(Expression.java:150)

晕,试了几下,原来加个刮号就没问题了。

<#if (fields?size>0) >
</#if>

[b][color=blue]关于Map[/color][/b]
非常重要的一点,[b][color=red]你的Map的key不能是一个自定义的Object,否则在map[key]时总会报map[key]的值为空的错。[/color][/b]虽然没有看到官方文档说key不能是Object,但我的实践是不行,最终我该用Key为string,value 为List<ClassA>才work,虽然key不能是自定义的Object,但value可以是任意的object.

遍历Map,下面的例子是遍历Map<String, List<ClassA>> map类型的map,注意要使用map[key]来获取value, map.get(key)报错,当然有可能我碰到的错误跟Freemarker的版本有关,也许某些版本就没有这些问题。
[/size]

<#if (latestAllocationsMap??)>
<#list latestAllocationsMap?keys as key>
<#assign allocations=latestAllocationsMap[key]>
<#if (allocations?size>0) >
<td align="left">
${key?if_exists}
<#list allocations as allocation>
${allocation.allocId?if_exists}
</#list>
</td>
</#if>
</#list>
</#if>


[b][color=blue]关于自增长操作符[/color][/b]
字符串列子

<#assign allocationId= "">
<#list allocations as allocation>
<#assign allocationId= allocationId + " " + allocation.allocId>
</#list>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值