[英]how to use macros with FreeMarker in spring mvc
嗨,我在spring mvc項目中工作,我想使用FreeMarker作為我的模板引擎,我在使用宏時遇到問題,我想用(頁腳,頁眉和菜單)創建母版頁或布局在我的其他頁面中使用,到目前為止,我正在做一個簡單的示例,但我無法使其正常工作,我在宏中放入的內容未顯示我的FreeMarker版本為2.3.21。
這是我的freemarker java類配置:
@Bean
public FreeMarkerConfigurer freemarkerConfig() {
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/");
freeMarkerConfigurer.setDefaultEncoding("UTF-8");
return freeMarkerConfigurer;
}
@Bean
public FreeMarkerViewResolver viewResolver() {
FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
viewResolver.setPrefix("");
viewResolver.setSuffix(".html");
viewResolver.setCache(false); //Set to true during production
viewResolver.setContentType("text/html;charset=UTF-8");
return viewResolver;
}
我將我的宏另存為.html頁面,例如myMacro.html
這是myMacro.html文件
<#macro myMasterPage title="defaultTitle">
<html>
<body style="width:100%;height:100%">
print me
<table border="1" cellspacing="0" cellpadding="0" style="width:100%;height:100%">
<tr>
<td colspan="2">
<#include "Header.html"/>
</td>
</tr>
<tr>
<td>
<#include "Menu.html"/>
</td>
<td>
<#nested/>
</td>
</tr>
<tr>
<td colspan="2">
<#include "Footer.html"/>
</td>
</tr>
</table>
</body>
</html>
</#macro>
這是我稱為宏的頁面
myPage.html下
[#import "/WEB-INF/views/myMacro.html" as layout /] [@layout.myMasterPage title="My test page"] ...content goes here... [/@layout.myMasterPage ]
我的footer.html
<div><h1>this is the footer</h1></di
我的header.html
<div><h1>this is the header</h1></div>
我的menu.html
<div>
<h1>
<ul>
<li>Menu item 1</li>
<li>Menu item 2</li>
<li>Menu item 3</li>
<li>Menu item 4</li>
<li>Menu item 5</li>
<li>Menu item 6</li>
</ul>
</h1>
</div>
這是我訪問myPage.html時得到的輸出
[#import "/WEB-INF/views/ApruebaFreeMarker.html" as layout /] [@layout.myMasterPage title="My test page"] ...content goes here... [/@layout.myMasterPage ]
這是我的控制器
@RequestMapping(value = "/myPage", method = RequestMethod.GET)
public String myPage(Model model) {
logger.info("PAge with Macro inside");
return "myPage";
}
編輯:我在導入布局時使用的是和其他語法:
[#import "/WEB-INF/views/ApruebaFreeMarker.html" as layout /] [@layout.myMasterPage title="My test page"] ...content goes here... [/@layout.myMasterPage ]
但我這樣編輯,它有效
<#import "myMacro.html" as layout>
<@layout.myLayout>
<div><h1>Hello Dude</h1></div>
</@layout.myLayout>
但是我還有另一個問題,我是freemarker的新手,我不知道如果將它們另存為.html或.ftl有什么區別?
您正在使用所謂的“替代(方括號)語法”。 在這里看看: http : //freemarker.org/docs/dgui_misc_alternativesyntax.html最有可能通過替換尖括號上的方括號解決問題,或者通過使用([#ftl]文檔)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.