Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FreeMarker recursive nested lists

I have a data structure that looks like this:

public class Foo {
    public Bar bar;
    public List<Foo> foos = new ArrayList<>();
}

Each instance of Foo can hold an arbitrary amount of FooS, which of course in turn can contain even more FooS and so on. So how would I go about making FreeMarker go through a list like that ?

like image 255
Torque Avatar asked Oct 27 '25 03:10

Torque


1 Answers

FreeMarker macros (and functions) support recursion. So something like this:

<#macro dumpFoo foo>
  ${foo.bar}
  <#list foo.foos as childFoo>
    <@dumpFoo childFoo />
  </#list>
</#macro>

<@dumpFoo myFoo />

Example data-model (using https://try.freemarker.apache.org/ syntax, but it works equally well with List-s and Foo beans):

myFoo = {
  "bar": "root",
  "foos": [
    {
      "bar": "child 1",
      "foos": [
        {
          "bar": "child 1.1",
          "foos": []
        }
      ]
    },
    {
      "bar": "child 2",
      "foos": []
    }
  ]
}

Output:

  root
  child 1
  child 1.1
  child 2
like image 96
ddekany Avatar answered Oct 28 '25 17:10

ddekany



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!