Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FreeMarker layouts to reduce template redundancy?

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?

like image 953
smeeb Avatar asked Nov 20 '15 17:11

smeeb


People also ask

What is the use of FreeMarker template?

FreeMarker is a template engine, written in Java, and maintained by the Apache Foundation. We can use the FreeMarker Template Language, also known as FTL, to generate many text-based formats like web pages, email, or XML files.

What is eval in FreeMarker?

eval. This built-in evaluates a string as an FTL expression. For example "1+2"? eval returns the number 3. (To render a template that's stored in a string, use the interpret built-in instead.)

What syntax is used to access data using FreeMarker under a condition?

Special variables are variables defined by the FreeMarker engine itself. To access them, you use the . variable_name syntax.

How do I use FreeMarker template in spring boot?

Freemarker Template FilesSpring boot looks for the The template files under classpath:/templates/. And for the file extension, you should name the files with . ftlh suffix since Spring Boot 2.2. If you plan on changing the location or the file extension, you should use the following configurations.


1 Answers

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);
like image 76
ddekany Avatar answered Oct 20 '22 17:10

ddekany