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)??.

posted @ 2013-04-09 14:23  Onakaumi  阅读(298)  评论(0编辑  收藏  举报