API / Apache FreeMarker Interview questions
How do you access the current loop position and detect the last item inside a #list block?
Inside <#list sequence as item>, FreeMarker exposes per-iteration built-ins on the loop variable itself: item?index gives the zero-based position, item?counter gives the one-based position, and item?has_next is true for every iteration except the last.
<#list tags as tag>${tag}<#if tag?has_next>, </#if></#list>
For the common "print a separator between items but not after the last one" pattern, the dedicated <#sep> directive inside the loop body is more idiomatic than a manual <#if> check:
<#list tags as tag>${tag}<#sep>, </#sep></#list>
Both approaches produce the same output; <#sep> exists specifically to make that intent explicit and avoid a stray trailing separator, which is a common off-by-one mistake when it is written out manually.
More Related questions...