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

dph*_*ham 14 spring-mvc thymeleaf

使用thymeleaf有一种方法来装饰我的布局w /我的页面特定的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>
Run Code Online (Sandbox Code Playgroud)

Tom*_*lst 45

在您的布局模板中,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>
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢!这有效,但无论如何不在div标签中包装它? (2认同)
  • 是的,而不是使用`<div>`标签,使用`<th:block>`标签.这将导致呈现的页面,而不是包装在div中.对我来说,从维护和开发的角度来看,术语"块"更明确地作为格式化构造,将在呈现的页面中删除 (2认同)
  • Spring Boot 默认从以下位置提供服务:`classpath:/META-INF/resources/`、`classpath:/resources/`、`classpath:/static/`、`classpath:/public/`。您可以在以下位置之一中静态资源:`src/main/resources/resources`、`src/main/resources/static`、`src/main/resources/public` 或`META-INF/resources` 文件夹. https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot (2认同)