We are trying to build a system in freemarker where extension files can be optionally added to replace blocks of the standard template.
We have gotten to this point
<#attempt>
<#include "extension.ftl">
<#recover>
Standard output
</#attempt>
So - if the extension.ftl file exists it will be used otherwise the part inside of the recover block is output.
The problem with this is that freemarker always logs the error that caused the recover block to trigger.
So we need one of two things:
- Don't call the include if the file doesn't exist - thus the need to check for file existence.
-OR-
- A way to prevent the logging of the error inside the recover block without changing the logging to prevent ALL freemarker errors from showing up.
I had this exact need as well but I didn't want to use FreeMarker's
ObjectConstructor
(it felt too much like a scriptlet for my taste).I wrote a custom FileTemplateLoader:
And my corresponding FreeMarker macro:
An empty FTL file was required (
/tools/empty.ftl
) which just contains a comment explaining its existence.The result is that an "optional" include will just include this empty FTL if the requested FTL cannot be found.
We've written a custom macro which solves this for us. In early testing, it works well. To include it, add something like this (where mm is a Spring ModelMap):
easier solution would be:
You can use also use Java method to check file exist or not.
Java Method-
Freemarker Code-
Try this to get the base path:
Then this to walk the directory structure: