Search code examples
freemarker

Print List to console in Table format


I'm looking for a Freemarker template that can output a List to console in tabular format.

<#list ["foo", "bar", "baz", "huhu", "lala", "keke", "koko", "fifi", "bubu"] as x>
${x}
</#list>

I'm looking for console output like:

foo      bar      baz
huhu     lala     keke
koko     fifi     bubu

I think ${x?item_cycle('col1', 'col2', 'col3')} maybe the way to go, adding a line break only for col3 items. But how can I do if else logic on item_cycle?


Solution

  • The nicest way of adding line breaks is probably with ?chunk(n). Also, the column width (which you haven't asked about) can for example be ensured with ?right_pad(n). So the example is:

    <#list ["foo", "bar", "baz", "huhu", "lala", "keke", "koko", "fifi", "bubu"]?chunk(3) as row>
      <#list row as x>${x?right_pad(10)}</#list>
    </#list>
    

    BTW, as you have asked, of course you can write things like <#if x?item_cycle(...) == ...>, or even ${x}${x?item_cycle('', '', '\n')}, or <#if x?item_count % 3 == 0>, but these are uglier solutions.