我只想做类似于这样的事情:
<a href="${ a? 'a.htm' : 'b.htm'}">
<#if>
和<#else>
。 - Jake TorontoRegistered: ${registered?string('yes', 'no')}
。从2.3.23开始有了condition?then(whenTrue, whenFalse)
来实现这一功能。 - ddekany<#macro if if then else=""><#if if>${then}<#else>${else}</#if></#macro>
它易于使用,外观漂亮且易读:
<@if someBoolean "yes" "no"/>
@if
而不是内置指令中的#if
。以下是更多示例。<!-- `else` is optional -->
<@if someBoolean "someBoolean is true"/>
<!-- expressions -->
<@if (someBoolean||otherBoolean) "hello,"+user.name 1+2+3 />
<!-- with parameter names -->
<@if someBoolean then="yes" else="no" />
<!-- first in list? -->
<#list seq as x>
<@if (x_index==0) "first" "not first"/>
<#list>
由于某种原因,如果它们是非布尔表达式,则无法在无名称参数周围添加括号。这可能会进一步提高可读性。
if
的自定义函数,声明方式如下:<#function if cond then else="">
<#if cond>
<#return then>
<#else>
<#return else>
</#if>
</#function>
${...}
表达式中使用。你的代码应该像这样:<a href="${if(a, 'a.htm', 'b.htm')}">
${...}
表达式中使用,而不是作为指令。<#assign targetUrl=if(a, 'a.htm', 'b.htm')/>
<a href="${targetUrl}">link 1</a>
...
<a href="${targetUrl}">link 2</a>
<!-- `else` is optional -->
${if(someBoolean, "someBoolean is true")}
<!-- expressions -->
${if(someBoolean||otherBoolean, "hello,"+user.name, 1+2+3)}
<!-- with parameter names: not possible with functions,
but also not really helpful -->
<!-- first in list? -->
<#list seq as x>
${if(x_index==0, "first", "not first")}
<#list>
a?then('a.htm', 'b.htm')
。使用condition?then(whenTrue, whenFalse)
相比于condition?string(whenTrue, whenFalse)
的优点是它适用于非字符串类型的whenTrue
和whenFalse
,而且它只计算whenTrue
和whenFalse
表达式中的一个(选择的分支)。使用插值语法:
"${(a?has_content)?string('a.htm','b.htm')}"
has_content: 可用于处理字符串(如果为空字符串,则返回FALSE)
。最初的回答。
?string
,但是a
的值确切是什么?您是想测试它是否存在,还是布尔值为true
? - ddekany