2016-03-26 49 views
6

平均标签库,我使用的是JSP标记做这样的事情:Thymeleaf是否有类似JSP标签的东西?

ChildPage.jsp

<%@ page contentType="text/html" pageEncoding="UTF-8" %> 
<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %> 

<t:layout> 
    <jsp:attribute name="head"> 
     <link href="css/custom.css" type="text/css" rel="stylesheet"/> 
    </jsp:attribute> 
    <jsp:attribute name="scripts"> 
     <script src="js/custom.js"></script> 
    </jsp:attribute> 
    <jsp:body> 
     <p>This is from the child page</p> 
    </jsp:body> 
</t:layout> 

layout.tag

<%@ tag description="Layout template" pageEncoding="UTF-8" %> 
<%@ attribute name="head" fragment="true" %> 
<%@ attribute name="scripts" fragment="true" %> 
<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <link href="css/main.css" type="text/css" rel="stylesheet"/> 
     <jsp:invoke fragment="head"/> 
    </head> 
    <body> 
     <div id="body"> 
      <p>This is from the parent or "layout"</p> 
      <jsp:doBody/> 
     </div> 
     <div id="footer"> 
      <script src="js/main.js"></script> 
      <jsp:invoke fragment="scripts"/> 
     </div> 
    </body> 
</html> 

呈现时

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <link href="css/main.css" type="text/css" rel="stylesheet"/> 
     <link href="css/custom.css" type="text/css" rel="stylesheet"/> 
    </head> 
    <body> 
     <div id="body"> 
      <p>This is from the parent or "layout"</p> 
      <p>This is from the child page</p> 
     </div> 
     <div id="footer"> 
      <script src="js/main.js"></script> 
      <script src="js/custom.js"></script> 
     </div> 
    </body> 
</html> 

这让我包括从布局和子页面两个JSP的标题部分脚本。身体和页脚也一样。

我已阅读Thymeleaf文档/示例,但也许我不正确理解,因为它看起来不像我可以做我想要实现的。

为什么我倒过来看起来像一个简单的包括每个页面,我包括某些脚本和标题部分,但我的子页面也有脚本被导入和样式表包括在内。

我能以这种方式实现吗?我做错了吗?

+0

你不想'th:replace'?就像' –

+0

@robertotomás我不想替换HTML''节点中的所有内容,我想合并内容。 – dkanejs

+0

我实际上并不明白你在做什么..我想如果你的例子有多个'jsp:invoke fragments',它会有所不同,但是在你提供它的情况下,你真的不能用简单的替换来做。 –

回答

3

默认Thymeleaf使用所谓的包含样式布局。这种方法的缺点explained在官方网站上。我建议你使用Thymeleaf Layout Dialect。这是创建层次式布局方便得多的方言。

顺便说一下,在Layout Dialect中,所有<head>标签的内容都会自动合并。只要看看example

+0

如上所述,我使用了Thymeleaf Layout Dialect。我会将我的解决方案附加到我的问题上。 – dkanejs

相关问题