Total Pageviews

2020/03/05

[Java] [Freemarker] How to ignore certain white-space

Problem
Here is my original ftl file:
<#if employees??>
<#list employees as e>
    ${e_index + 1}. ${e.name?right_pad(10)} - 
    <#switch e.gender>
        <#case "M">男<#break>
        <#case "F">女<#break>
        <#default>No matching gender found.
    </#switch>
</#list>
<#else>
No data found.
</#if>

But it had unexpected outcome:
    1. Albert     -
男    2. Mandy      -
女    3. Mia        -
女    4. Eric       -
男


How-To
Making use of #rt to ignore all railing white-space and add one enter at the end of switch. The updated ftl file looks like:
<#if employees??>
<#list employees as e>
    <#-- using <#rt> (for right trim) to ignore all 
         trailing white-space in this line. -->
    ${e_index + 1}. ${e.name?right_pad(10)} - <#rt>
    <#switch e.gender>
        <#case "M">男<#break>
        <#case "F">女<#break>
        <#default>No matching gender found.
    </#switch>
    <#-- 多按一個 enter 才會換行 -->

</#list>
<#else>
No data found.
</#if>



Check the result:
    1. Albert     - 男
    2. Mandy      - 女
    3. Mia        - 女
    4. Eric       - 男



Reference
[1] https://freemarker.apache.org/docs/ref_directive_t.html

No comments: