Thymeleaf:如何使用布局包含页面特定的javascript?

时间:2014-04-22 09:33:23

标签: spring-mvc thymeleaf

使用thymeleaf是否有办法用我的页面特定的javascript和javascript包含我的布局?

<!--My Layout -->
<!DOCTYPE html>
<html>
<head>

</head>
<body>
<div th:replace="fragments/header :: header">

</div>
<div class="container">
    <div layout:fragment="content">

    </div>
</div>
</body>
</html>

<!--My Page -->
<!DOCTYPE html>
<html layout:decorator="layout">
<head>

</head>
<body>

<div layout:fragment="content">
    hello world
</div>

<script src="pageSpecific1.js"></script>
<script src="pageSpecific2.js"></script>
<script>
 alert("hello world")
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:38)

在您的布局模板中,为脚本添加fragment

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
    <body>
       ..
       <th:block layout:fragment="script"></th:block>
    </body>
</html>

然后在您的页面模板中,您可以添加该页面的脚本。

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
    layout:decorator="template.html">
    <body>
       ...
       <th:block layout:fragment="script">
            <script th:src="@{/page.js}"></script>
            <script>
                 function foo() {
                    ...
                 }
            </script>
       </th:block>
    </body>
</html>

不要忘记在页面模板中设置layout:decorator