Biscuit128
Biscuit128

Reputation: 5398

Freemarker - creating multiple child tags

Given an ftl file which is structured as below (just an example) i am able to replace / insert all elements in to level 1 which is fine.

My confusion arises when there maybe multiple level2's - for example it could repeat many times. As such my process for replacing will hit a pain point

<parent>
    <level1>
        <a>${a}</a>
        <b>${b}</b>
        <c>${c}</c>
        <d>${d}</d>
    </level1>
    <level2>
        <e><${e}</e>
        <f><${f}</f>
        <g><${g}</g>
        <h><${h}</h>
        <i><${i}</i>
        <j><${j}</j>
    </level2>
</parent>

    map.put("a", "valuefora");
    map.put("b", "valueforb");
    map.put("c", "valueforc");
    map.put("d", "valueford");

    Configuration cfg = new Configuration();
    cfg.setDirectoryForTemplateLoading(new File("C:\\templates"));
    Template temp = cfg.getTemplate("freemarker.ftl");
    Writer out = new OutputStreamWriter(System.out);
    temp.process(map, out);

At this point here - assuming i have a list of values to have multiple level2 nodes - how would i go about producing this using the style shown above?

Thanks

Upvotes: 8

Views: 870

Answers (1)

Hendrik Jander
Hendrik Jander

Reputation: 5715

I am not sure if i really understand your question, but i think you would just use the freemarker list-command. You would put Maps or Lists in your context. The list-command is documented here

<#list your.object.or.map as listElem>
  <level2>
     <e>${listElem.e}</e>
     <f>${listElem.f}</f>
   </level2>
</#list>

Your context object, just needs an according map or object.

The quickstart guide(see The list directive) also contains an example for using the list directive.

Upvotes: 2

Related Questions