在freemarker中使用三元运算符?

Jac*_* Hu 41 java freemarker

我只是想做这样的事情:

<a href="${ a? 'a.htm' : 'b.htm'}">
Run Code Online (Sandbox Code Playgroud)

obo*_*ain 75

如果您使用的是freemarker 2.3.23或更高版本,则可以使用then内置的:

<a href="${a?then('a.htm','b.html')}" target="${openTarget}">
Run Code Online (Sandbox Code Playgroud)

如果您使用的是旧版本的freemarker,则可以使用string内置版本:

<a href="${a?string('a.htm','b.html')}" target="${openTarget}">
Run Code Online (Sandbox Code Playgroud)

当应用于布尔值时,string内置函数将充当三元运算符.


  • 乍一看这是不是很明显.我赞成了答案,但老实说可能更容易理解`<#if>`和`<#else>` (4认同)
  • 它的可读性不是很好,因为这不是它的预期用途。它用于格式化布尔值,例如`Registered: ${registered?string('yes', 'no')}`。从 2.3.23 开始,这里有 `condition?then(whenTrue, whenFalse)`。 (3认同)

kap*_*pex 6

这个宏提供了一种更简单的三元运算方式:

<#macro if if then else=""><#if if>${then}<#else>${else}</#if></#macro>
Run Code Online (Sandbox Code Playgroud)

它易于使用,看起来很好,非常易读:

<@if someBoolean "yes" "no"/>
Run Code Online (Sandbox Code Playgroud)

请注意它是@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> 
Run Code Online (Sandbox Code Playgroud)

出于某种原因,如果它们是非布尔表达式,则无法在无名参数周围添加括号.这可能会提高可读性.