Thymeleaf模板-有没有办法装饰模板而不是包含模板片段?
问题内容:
我是第一次与Thymeleaf合作,我需要对模板进行说明。如果我正确地理解了文档,则可以在页面中 包含
模板(或只是其中的一部分)。因此,例如,我可以这样写:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head th:include="template/layout :: header">
</head>
<body>
Hello world
<div th:include="template/layout :: footer"></div>
</body>
</html>
但我想其实是在使用模板的相反的方式:不是,包括页面模板片段,我想包括在网页 中 我的模板,类似的东西:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
...
</head>
<body>
<div id="my-template-header">...</div>
<div id="the-content">
<!-- include here the content of the current page visited by the user -->
???
</div>
<div id="my-template-footer">...</div>
</body>
换句话说,有没有办法在Thymeleaf中具有等效的Sitemesh装饰器标签?
谢谢
问题答案:
好的,如Sotirios Delimanolis所述,Thymeleaf不支持这种使用模板的方式,或者我应该说“ 分层布局 ”,正如Daniel
Fernandez在此主题中所解释的那样。
由于sitemesh和Thymeleaf是兼容的,因此似乎必须同时使用这两种解决方案。太糟糕了。
编辑:正如DennisJaamann在评论中建议的那样,我最终使用了Thymeleaf Layout
Dialect
,这是一种提供我所需要的功能的视图方言。
工作代码:
首先,我添加LayoutDialect
类:
@Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
//NB, selecting HTML5 as the template mode.
resolver.setTemplateMode("HTML5");
resolver.setCacheable(false);
return resolver;
}
然后,创建模板(例如templates/layout.html
),并将layout:fragment
信息添加到要放置当前页面内容的位置:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
...
</head>
<body>
<div id="my-template-header">...</div>
<div id="the-content" layout:fragment="content">
<!-- include here the content of the current page visited by the user -->
</div>
<div id="my-template-footer">...</div>
</body>
并且页面将引用具有属性的模板layout:decorator
:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="templates/layout">
<body>
<div layout:fragment="content">
Hello world
</div>
</body>
</html>