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>
The layout page is similar to any other HTML page. However, you must add the xmlns:layout attribute to the html tag. Next, you need to specify the part of the layout page where you want the content to appear. This is done using a div tag with the fragment attribute.
We load the stylesheet using the link tag with Thymeleaf's special th:href attribute. If we've used the expected directory structure, we only need to specify the path below src/main/resources/static. In this case, that's /styles/cssandjs/main. css.
Basic inclusion with th:insert and th:replace Thymeleaf can include parts of other pages as fragments (whereas JSP only includes complete pages) using th:insert (it will simply insert the specified fragment as the body of its host tag) or th:replace (will actually substitute the host tag by the fragment's).
The JAVASCRIPT template mode will allow the processing of JavaScript files in a Thymeleaf application. This means being able to use model data inside JavaScript files in the same way it can be done in HTML files, but with JavaScript-specific integrations such as specialized escaping or natural scripting.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With