如何检查变量是否存在于Freemarker模板中?

我有一个FreeMarker模板,它包含一组占位符,在处理模板时会为这些占位符提供值。如果提供了username变量,我想有条件地包含模板的一部分,如下所示:

[#if_exists userName]
Hi ${userName}, How are you?
[/#if_exists]

然而,FreeMarker手册似乎指出,如果_存在是不赞成的,但我找不到另一种方法来实现这一点。当然,我可以简单地提供一个额外的布尔变量isUserName,并像这样使用它:

[#if isUserName]
Hi ${userName}, How are you?
[/#if]

但是,如果有一种方法可以检查用户名是否存在,那么我就可以避免添加这个额外的变量。

291571 次浏览

To check if the value exists:

[#if userName??]
Hi ${userName}, How are you?
[/#if]

Or with the standard freemarker syntax:

<#if userName??>
Hi ${userName}, How are you?
</#if>

To check if the value exists and is not empty:

<#if userName?has_content>
Hi ${userName}, How are you?
</#if>

Also I think if_exists was used like:

Hi ${userName?if_exists}, How are you?

which will not break if userName is null, the result if null would be:

Hi , How are you?

if_exists is now deprecated and has been replaced with the default operator ! as in

Hi ${userName!}, How are you?

the default operator also supports a default value, such as:

Hi ${userName!"John Doe"}, How are you?

This one seems to be a better fit:

<#if userName?has_content>
... do something
</#if>

http://freemarker.sourceforge.net/docs/ref_builtins_expert.html

I think a lot of people are wanting to be able to check to see if their variable is not empty as well as if it exists. I think that checking for existence and emptiness is a good idea in a lot of cases, and makes your template more robust and less prone to silly errors. In other words, if you check to make sure your variable is not null AND not empty before using it, then your template becomes more flexible, because you can throw either a null variable or an empty string into it, and it will work the same in either case.

<#if p?? && p?has_content>1</#if>

Let's say you want to make sure that p is more than just whitespace. Then you could trim it before checking to see if it has_content.

<#if p?? && p?trim?has_content>1</#if>

UPDATE

Please ignore my suggestion -- has_content is all that is needed, as it does a null check along with the empty check. Doing p?? && p?has_content is equivalent to p?has_content, so you may as well just use has_content.

For versions previous to FreeMarker 2.3.7

You can not use ?? to handle missing values, the old syntax is:

<#if userName?exists>
Hi ${userName}, How are you?
</#if>