I have a lot of different FreeMarker templates inside my Java Spring Boot application and all of them share certain elements as for example a header and footer. Is it possible to build reusable components as one would in Angular or React?
I thought about creating elements as objects in Java and then importing them to FreeMarker as one would import text, but I thought there may be a more elegant solution.
FreeMarker supports import and include.
But:
Using include directive is almost always a bad practice, and you should consider using the import directive instead!
I went on using import, more about when to use import here.
If you want to f.e. import a header component you would create a components.ftl file and create a macro inside.
components.ftl:
<#macro header>
<header>
<p>My first FreeMarker macro component header</p>
</header>
</#macro>
You can now import the header macro to your FreeMarker template:
template.ftl
<#import "template-components/components.ftl" as components>
...
<@components.header/>
Your header component should now display when loading the template.
Macros also support variables and lots more. I recommend visiting the links mentioned.