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

标签 spring-mvc 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>

最佳答案

在布局模板中,为脚本添加一个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

关于spring-mvc - Thymeleaf:如何使用布局包含特定于页面的javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23215705/

相关文章:

Java - 从数据库获取用户名

java - Spring MVC + Thymeleaf 将单个对象发送到 Controller

java - 如何映射 url 中的项目列表 RequestMapping

javascript - Thymeleaf/JavaScript 保留动态填充的选择元素的值

java - Spring为构造函数注入(inject)依赖

spring - @PathVariable 和@ModelAttribute 的区别

java - Thymeleaf 中的模块化模板解析器

java - 使用 thymeleaf 在 spring mvc 应用程序中从数据库生成 html 选择选项

java - 区分是否是重定向: or a normal request in HandlerInterceptorAdaptor

java - Spring mvc maven - 添加库