Index

Freemarker

Hello World

public static void main(String[] args) throws IOException, TemplateException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);

        StringTemplateLoader tl = new StringTemplateLoader();
        tl.putTemplate("bla", "blabla ${test} blabla");
        cfg.setTemplateLoader(tl);
        Template template = cfg.getTemplate("bla");

        // Build the data-model
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("test", "Hello World!");

        // Console output
        Writer out = new OutputStreamWriter(System.out);
        template.process(data, out);
        out.flush();
}
loading templates from the classpath
TemplateLoader ctl = new ClassTemplateLoader(getClass(), "/freemarker");
cfg.setTemplateLoader(ctl);
cfg.getTemplate("filename.tpl")
loading templates from the filesystem
TemplateLoader ftl = new FileTemplateLoader(new File(templatePath));
chaining multiple template loaders
TemplateLoader mtl = new MultiTemplateLoader(new TemplateLoader[] { ftl, ctl });
storing the result in a String
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(baos);
cfg.getTemplate(template).process(data, writer);
writer.flush();
return baos.toString("UTF-8");

basics

assign variable
<#assign x = 1>
optional value
${(log)!}
section depending on optional value
<#if log??>
    ${log}
</#if>
string comparison
<#if someString == someOtherString>
<#if someString != someOtherString>
read a value from a map
${map[key]}
print variable without readability characters (numbers without commas, etc)
${question.id?c}
defining a sequence
<#assign values = ["a", "b"]>
<#list seq[1..3] as i>${i}</#list>
accessing a value from a sequence
${values[0]}
include another template
<#include "layout/bottom.tpl"/>

control flow

ternary operator
${result.incorrect ? then ('incorrect', 'visible')}
if else
<#if condition>
  ...
<#elseif condition>
  ...
<#else>
  ...
</#if>
iterating a sequence
<#list values as value>
	<h1>${value}</h1>
</#list>
for each loop
<#list someList as entry>
	${entry.someProperty}
</#list>

Tree structures

navigating a tree structure
<#macro tree nodes>
  <#list nodes.getChildren() as node>
    <ul>
      <li>
        ${node.getName()}
        <#if node.hasChildren()>
          <@tree nodes=node />
        </#if>
      </li>
    </ul>
  </#list>
</#macro>
to call
<@tree nodes=root/>
sample tree node
public class TreeNode {
	private List<TreeNode> children = new ArrayList<>();
	private String name;

	public TreeNode(String name) {
		this.name = name;
	}

	public List<TreeNode> getChildren() {
		return children;
	}

	public String getName() {
		return name;
	}

	public boolean hasChildren() {
		return !children.isEmpty();
	}
}

Links

try freemarker code online
https://try.freemarker.apache.org/