I had this exact need, but I did not want to use the FreeMarker ObjectConstructor (it looked too much like a scriptlet for my taste).
I wrote a custom FileTemplateLoader :
public class CustomFileTemplateLoader extends FileTemplateLoader { private static final String STUB_FTL = "/tools/empty.ftl"; public CustomFileTemplateLoader(File baseDir) throws IOException { super(baseDir); } @Override public Object findTemplateSource(String name) throws IOException { Object result = null; if (name.startsWith("optional:")) { result = super.findTemplateSource(name.replace("optional:", "")); if (result == null) { result = super.findTemplateSource(STUB_FTL); } } if (result == null) { result = super.findTemplateSource(name); } return result; } }
And my corresponding FreeMarker macro:
<#macro optional_include name> <#include "/optional:" + name> </#macro>
Requires an empty FTL file ( /tools/empty.ftl ), which contains a comment explaining its existence.
As a result, an βoptionalβ include will include this empty FTL if the requested FTL is not found.
Stano
source share