Use ternary operator in freemarker?

后端 未结 5 901
忘了有多久
忘了有多久 2021-02-01 12:54

I just want to do something like this:


5条回答
  •  孤街浪徒
    2021-02-01 13:38

    This macro provides a more straightforward way to do ternary operations:

    <#macro if if then else=""><#if if>${then}<#else>${else}
    

    It's easy to use and looks nice and quite readable:

    <@if someBoolean "yes" "no"/>
    

    Note that it is @if - and not #if as in the built-in directive. Here are some more examples.

    
    <@if someBoolean "someBoolean is true"/>  
    
    
    <@if (someBoolean||otherBoolean)  "hello,"+user.name  1+2+3 />  
    
    
    <@if someBoolean then="yes" else="no" />  
    
    
    <#list seq as x>
        <@if (x_index==0)  "first"  "not first"/> 
    <#list> 
    

    For some reason you can't add parenthesis around nameless parameters, if they are non-boolean expressions. That could have increased readability even more.

提交回复
热议问题