Search code examples
javafreemarker

How to implement a custom counter in freemarker?


I have a list that I am iterating over but I want to use my own counter. I have tried with several unsuccessful attempts to implement my own counter. The built in functions will not work as some records are filtered out of the list on the fly but I want to only count the records that are not filtered. I tried assigning a value to a variable and incrementing but always seemed to repeat the value.

sample code

 <#list recordList as record>
    <#assign count>${record_index + 1 }</#assign>
    <#if record.isNotExcluded()>            
        <#lt> Record ${count}   
    </#if> 
</#list>

In the example above if I have 5 records and third record is excluded then it throws the numbering off.


Solution

  • You have to assign the count outside of the for-loop:

    <#assign count = 0>
    
    <#list recordList as record>
        <#if record.isNotExcluded()>            
            <#lt> Record ${count}   
            <#assign count = count + 1>
        </#if> 
    </#list>
    

    Edit: As a best practice the data the backend is sending to the view should already have the excluded items filtered out. That is business logic and shouldn't be done in the FreeMarker view. The backend should only send the data that is needed so that logic like this can be avoided.