Christopher
Christopher

Reputation: 53

How do I create a Freemarker template with n depth?

I am trying to use Apache Freemarker to display some data in a json-esque format that is n layers deep. With this unknown, I am trying to output something similar to below:

{
  "name": "Human",
  "type": "object",
  "fields": [
    {
      "name": "weight"
      "type": "int"
    },
    {
      "name": "Origin"
      "type": "object"
      "fields": [
        {
          "name": "fatherOrigin"
          "type": "object"
          "fields": [
             ... 
          ]
        },
        {
          "name": "motherOrigin"
          "type": "object"
          "fields": [
             ... 
          ]
        }]
    }]
}

I wanted to use a while loop that, in pseudocode, looks like this.

while(1){
  if (currType is object) {
      print what you know and walk deeper
   }else{
      print your output and break
  }

However, freemarker does not support while loops. My alternative is to create a list that that is of a size that is larger than any reasonable depth (30)

Is this an accepted design for this problem? Is there a better way to approach it?

Thanks!

Upvotes: 0

Views: 260

Answers (1)

ddekany
ddekany

Reputation: 31122

There's no while loop indeed. The cleanest way I can imagine is <#list 0.. as _>...</#list>, but beware, 0.. will only work properly (as an infinite series) with high enough incompatible_improvements configuration setting value. _ is just a plain variable, but meant to express that I don't care about the name.

But, generally, processing nested structures is best done with recursion. Macros and functions support that. Then #list-s (if you will need them at all) usually go through an actual list of things that's coming from the data-model, not some range you have constructed as a workaround.

Upvotes: 1

Related Questions