2013-07-09 4391 views

回答

49

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

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

如果您使用的freemarker的是旧版本,你可以使用,而不是建立在string式中:

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

当应用于布尔值,该string内置将作为三元操作符。


+4

乍一看这并不明显。我提高了答案,但是说实话,只要做一个'<#if>'和'<#else>' –

+0

就可以读得更清楚了,因为这不是它的预期用法。它用于格式化布尔值,如'Registered:$ {registered?string('yes','no')}'。从2.3.23开始,有条件吗?那么(whenTrue,whenFalse)'。 – ddekany

+0

@ddekany感谢您提供的信息,我更新了包含新解决方案的答案。 – obourgain

6

该宏提供一种更简单的方式做三元操作:

<#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> 

由于某些原因,如果它们是非布尔表达式,不能在无名参数周围添加括号。这可能会提高可读性。

1

您可以自定义一个函数if即宣告像这样:

<#function if cond then else=""> 
    <#if cond> 
    <#return then> 
    <#else> 
    <#return else> 
    </#if> 
</#function> 

功能可以在任何${...}表达式中使用。您的代码看起来像这样:

<a href="${if(a, 'a.htm', 'b.htm')}"> 

相反@kapep,我认为你应该使用的函数,而不是宏。 宏产生(文本)输出,而函数返回的值可以分配给变量,但也写入输出,因此使用函数更灵活。此外,应用函数的方法更接近于使用三元运算符,它也可用于${...}表达式中,而不是作为指令使用。

例如,如果您需要有条件的链接目标多次,这将使意义将其分配到一个局部变量:

<#assign targetUrl=if(a, 'a.htm', 'b.htm')/> 
<a href="${targetUrl}">link 1</a> 
... 
<a href="${targetUrl}">link 2</a> 

使用功能,而不是宏观的,@ kapep的例子会是什么样子这个:

<!-- `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> 
3

从FreeMarker 2.3.23开始,你可以写a?then('a.htm', 'b.htm')condition?then(whenTrue, whenFalse)优于condition?string(whenTrue, whenFalse)的优点是它适用于非字符串whenTruewhenFalse,并且它仅评估whenTruewhenFalse表达式(无论哪个分支被选中)之一。