根据FreeMarker的 include
statement docs,您可以像这样制作可识别页眉和页脚的模板:
<#include "/header.ftl">
<!-- Content of my this page -->
<#include "/footer.ftl">
但是,如果我的Web应用程序具有数百个页面/ View ,则这是很多多余的复制面食。如果在FreeMarker中有一个类似“布局”的概念,那我会说:“嘿,这是一个布局:”
<#include "/header.ftl">
<@import_FTL_Somehow>
<#include "/footer.ftl">
然后为每个 View /页面(
index.ftl
,contactUs.ftl
等)创建单独的模板,然后告诉FreeMarkers哪个FTL文件“使用”布局。这样,我将不必继续指定每个模板文件中包含的页眉/页脚。FreeMarker是否支持这种概念?
最佳答案
不需要,但是如果您只需要页脚或页眉,可以通过一些TemplateLoader
hack(在TemplateLoader
插入页眉和页脚代码段的方式来解决,就像在模板文件中一样)来解决。但是FreeMarker中通常的解决方案是从每个模板中显式调用布局代码,但不直接使用两个#include
-s,而是:
<@my.page>
<!-- Content of my this page -->
</@my.page>
其中
my
是自动导入的(请参阅Configuration.addAutoImport
)。更新:另一种方法是您有一个类似于
layout.ftl
的代码:Heading stuff here...
<#include bodyTemplate>
Footer stuff here...
然后,从Java中,您总是调用
layout.ftl
,而且还使用bodyTemplate
变量传入主体模板名称:dataModel.put("bodyTemplate", "/foo.ftl");
cfg.getTemplate("layout.ftl").process(dataModel, out);
关于layout - FreeMarker布局以减少模板冗余?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33832426/