【问题标题】:Thymeleaf: how to include page specific javascript using layouts?Thymeleaf:如何使用布局包含特定于页面的 javascript?
【发布时间】:2014-06-06 14:21:43
【问题描述】:

使用 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>

【问题讨论】:

  • 你到底想做什么?将javascript移动到布局中?还是我误解了这个问题?
  • 您的 javascript 存储在哪里? thymeleaf 模板怎么样?

标签: spring-mvc thymeleaf


【解决方案1】:

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

【讨论】:

  • 很酷,谢谢!这可行,但无论如何不要将其包装在 div 标签中?
  • 是的,不要使用&lt;div&gt; 标签,而是使用&lt;th:block&gt; 标签。这将导致呈现的页面不被包裹在 div 中。对我来说,从维护和开发的角度来看,block 一词作为一种格式结构更为明确,将在呈现的页面中删除
  • JavaScript 文件page.js 需要在哪里才能正确加载/page.js?我正在使用 SpringBoot 并将我的 .js 文件与 thymeleaf 模板放在同一文件夹中 - /src/main/resources/ - 但 /page.js 没有找到它。
  • Spring Boot 默认从以下位置提供服务:classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public/。您可以在以下位置之一中静态资源:src/main/resources/resourcessrc/main/resources/staticsrc/main/resources/publicMETA-INF/resources 文件夹。 spring.io/blog/2013/12/19/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-22
  • 2020-05-26
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多