freemarker null

Dealing with missing variables

In practice the data-model often has variables that are optional (i.e., sometimes missing). To spot some typical human mistakes, FreeMarker doesn't tolerate the referring to missing variables unless you tell them explicitly what to do if the variable is missing. Here we will show the two most typical ways of doing that.

Note for programmers: A non-existent variable and a variable with null value is the same for FreeMarker, so the "missing" term used here covers both cases.

Wherever you refer to a variable, you can specify a default value for the case the variable is missing, by following the variable name with a ! and the default value. Like in the following example, whenuser is missing from data model, the template will behave like if user's value were the string"Anonymous". (When user isn't missing, this template behaves exactly like if !"Anonymous"were not there):

<h1>Welcome ${user!"Anonymous"}!</h1> 

You can ask whether a variable isn't missing by putting ?? after its name. Combining this with the already introduced if directive you can skip the whole greeting if the user variable is missing:

<#if user??><h1>Welcome ${user}!</h1></#if> 

Regarding variable accessing with multiple steps, like animals.python.price, writinganimals.python.price!0 is correct only if animals.python is never missing and only the last subvariable, price, is possibly missing (in which case here we assume it's 0). If animals orpython is missing, the template processing will stop with an "undefined variable" error. To prevent that, you have to write (animals.python.price)!0. In that case the expression will be 0 even if animals or python is missing. Same logic goes for ??; animals.python.price?? versus(animals.python.price)??.

转载于:https://www.cnblogs.com/xiaoyee/archive/2013/04/09/freemarker.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值