问题描述
我有一个Freemarker模板,其中包含一堆占位符,在处理模板时会为其提供值。如果提供了userName变量,我想有条件地包含模板的一部分,例如:
I have a Freemarker template which contains a bunch of placeholders for which values are supplied when the template is processed. I want to conditionally include part of the template if the userName variable is supplied, something like:
[#if_exists userName]
Hi ${userName}, How are you?
[/#if_exists]
但是,FreeMarker手册似乎表明不推荐使用if_exists ,但我找不到另一种方法来实现这一目标。当然,我可以简单地提供一个额外的布尔变量isUserName并使用如下:
However, the FreeMarker manual seems to indicate that if_exists is deprecated, but I can't find another way to achieve this. Of course, I could simple providing an additional boolean variable isUserName and use that like this:
[#if isUserName]
Hi ${userName}, How are you?
[/#if]
但是如果有办法检查userName是否存在那么我可以避免添加这个额外的变量。
But if there's a way of checking whether userName exists then I can avoid adding this extra variable.
推荐答案
检查价值是否存在:
[#if userName??]
Hi ${userName}, How are you?
[/#if]
或者使用标准的freemarker语法:
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>
这篇关于如何检查FreeMarker模板中是否存在变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!