Search code examples
javacode-generationfreemarker

How to create multiple files based on one Freemarker Template


I'm having a little bit trouble with freemarker right now. What I want to do basically in my template: iterate over a list of elements and create for each element a new file.

<#assign x=3>
<#list 1..x as i>
  ${i}
...create a new file with the output of this loop iteration...
</#list>

I did not find anything about this in the freemarker manual or google. Is there a way to do this?


Solution

  • You can implement this with a custom directive. See freemarker.template.TemplateDirectiveModel, and particularly TemplateDirectiveBody. Custom directives can specify the Writer used in their nested content. So you can do something like <@output file="...">...</@output>, where the nested content will be written into the Writer you have provided in your TemplateDirectiveModel implementation, which in this case should write into the file specified. (FMPP does this too: http://fmpp.sourceforge.net/qtour.html#sect4)