Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Thymeleaf have something like JSP tags?

I don't mean taglibs, I'm using a JSP tag to do something like this:

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>

When rendered:

<!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>

This allows me to include scripts in the header section of the JSP from both the layout and child pages. Same for the body and footer.

I've read through Thymeleaf docs/examples but maybe I'm not understanding correctly as it doesn't look like I can do what I am trying to achieve.

The reason why I have "inverted" what seems like a simple include is every page that I have includes certain scripts and a header section, but my child pages also have scripts to be imported and stylesheets to be included.

Can I achive this somehow? Am I doing this wrong?

like image 861
syncdk Avatar asked Mar 26 '16 01:03

syncdk


1 Answers

By default Thymeleaf uses so called Include-style layouts. Disadvantages of this approach explained on official site. I would advise you to use Thymeleaf Layout Dialect. This is much more convenient dialect to create Hierarchical-style layouts.

By the way, in Layout Dialect all content of <head> tag will be merged automatically. Just take a look on example.

like image 107
Ken Bekov Avatar answered Oct 17 '22 15:10

Ken Bekov