Reputation: 29537
According to the FreeMarker include
statement docs, you can make header- and footer- aware templates like so:
<#include "/header.ftl">
<!-- Content of my this page -->
<#include "/footer.ftl">
But if my web app has hundreds of pages/views, this is a lot of redundant copy pasta. It would be great if there was like a "layout" concept in FreeMarker, where I could say "Hey, here is a layout:"
<#include "/header.ftl">
<@import_FTL_Somehow>
<#include "/footer.ftl">
And then create separate templates for each view/page (index.ftl
, contactUs.ftl
, etc.) and then tell FreeMarkers which FTL files "use" the layout. That way I wouldn't have to keep specifying header/footer includes in each and every template file.
Does FreeMarker support this kind of concept?
Upvotes: 10
Views: 5040
Reputation: 31152
It doesn't, though if you only need a footer or header it can be solved with some TemplateLoader
hack (where the TemplateLoader
inserts the header and footer snippets, as if was there in the template file). But the usual solution in FreeMarker is calling the layout code explicitly from each templates, but not with two #include
-s directly, but like:
<@my.page>
<!-- Content of my this page -->
</@my.page>
where my
is an auto-import (see Configuration.addAutoImport
).
Update: Another approach is that you have a layout.ftl
like:
Heading stuff here...
<#include bodyTemplate>
Footer stuff here...
And then from Java you always call layout.ftl
, but also pass in the body template name using the bodyTemplate
variable:
dataModel.put("bodyTemplate", "/foo.ftl");
cfg.getTemplate("layout.ftl").process(dataModel, out);
Upvotes: 9