Search code examples
javafreemarker

How do I tell free marker to skip a <sep> directive in a list iteration?


I am trying to iterate over a JSON object in a <#list> iteration in Freemarker and write out the same JSON in a different form. For some conditions, I'd like to skip over the iteration and not write out anything, but Freemakrer still writes out the comma because I use the separator directive: <#sep>,</#sep>.

For example

"<#list .data_model as key, value>" +
    "<#if key == 'someVal1' || key == 'someVal2' || value?is_hash>" + //do nothing for these
    "<#else>" +
        "\"${key}\":\"${value?json_string?json_string}\"<#sep>,</#sep>" +
    "</#if>" +
"</#list>"

The output is something like:

{"aval1":"1",,"aval2":["item"], ...}

Notice the duplicate commas.

In other places I have implemented some special logic where I write out a comma for the previous item, so long as the current item is not the first item. The logic works but seems weird to have to duplicate.

Are there any Freemarker built-ins for this kind of situation?


Solution

  • Found a way to work around:

    "<#assign x=false><#list .data_model as key, value>" +
    "<#if key == 'someVal1' || key == 'someVal2' || value?is_hash>" + //do nothing for these
    "<#else>" +
        "<#if x>,</#if>\"${key}\":\"${value?json_string?json_string}\"<#assign x=true>" +
    "</#if>" +
    "</#list>"