Thymeleaf: how to include page specific javascript using layouts?

dpham picture dpham · Apr 22, 2014 · Viewed 36.1k times · Source

Using thymeleaf is there a way to decorate my layout w/ my page specific javascript and javascript includes?

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

Answer

Tom Verelst picture Tom Verelst · Apr 22, 2014

In your layout template, put a fragment for the script.

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

And in your page template, you can then add the script for that page.

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

Don't forget to set the layout:decorator in your page template.