In django I can do:
<head>
{% block content %}
(....) ---------> content from a partial template goes here.
{% endblock %}
(....) ---------> I can add aditional stuff here if I need to.
<head>
wherever I like. (example: use the same head in all templates but one page requires an aditional css file or script)
I understand that In thymeleaf I need to define an entire tag as a fragment to which I can no longer add anything else and need to use as is.
My question is how would I go about to achieve the above example in thymeleaf?
The first part of the statement, fragments/header , is a template name that we are referencing. This can be a file (like in this example) or it can reference to the same file either by using the this keyword (e.g. this :: header ) or without any keyword (e.g. :: header ).
While Thymeleaf is more of a template engine for server-side application development. But Thymeleaf's popularity is on a steady rise. The developer community is slowly moving away from 'once a common' MVC framework for Javascript-based development.
Thymeleaf is an XML/XHTML/HTML5 template engine (extensible to other formats) that can work both in web and non-web environments. It is better suited for serving XHTML/HTML5 at the view layer of web applications, it can process any XML file even in offline environments.
If you are building web front-ends with Spring Boot or Spring MVC, and you're still using JSP (Java Server Pages) then this course is for you. Thymeleaf is a great templating engine which replaces JSP, and you can easily use it in any Spring MVC or Spring Boot application. Unlike JSP it's a pleasure to use.
Create a folder under resources/templates called fragments. After create a file fragment.html then in your head:
<head>
<div th:replace="fragments/fragment :: fragment"></div>
(....) ---------> you can add aditional stuff here if you need to.
<head>
And in your fragment.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head></head>
<body>
<div th:fragment="fragment" th:remove="tag">
(....) ---------> content from a partial template goes here.
</div>
</body>
</html>
th:replace will actually substitute the host tag by the fragment’s
th:remove="tag" removed the container div of the fragment included
As a result you should get:
<head>
(....) ---------> content from a partial template goes here.
(....) ---------> you can add aditional stuff here if you need
<head>
Just add this into head tag
<head>
<th:block th:replace="fragments/headContent :: baseContent"></th:block>
<!-- other blocks -->
</head>
In Fragment file
<head>
<th:block th:fragment="baseContent">
<link href="/css/bootstrap.min.css" rel="stylesheet">
<style> **your style tag content** </style>
</th:block>
</head>
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