📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
- How to add CSS and JS files to Thymeleaf templates.
- How to use CSS and JavaScript in our Thymeleaf templates.
Learn Thymeleaf at https://www.javaguides.net/p/thymeleaf-tutorial.html
Add Maven Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Thymeleaf Example with Spring Boot
1. Folder Structure
- By default, Thymeleaf expects us to place those templates in the src/main/resources/templates folder.
- For CSS and JavaScript files, the default directory is src/main/resources/static.
2. Adding CSS
h2 {
font-family: sans-serif;
font-size: 1.5em;
text-transform: uppercase;
}
strong {
font-weight: 700;
background-color: yellow;
}
p {
font-family: sans-serif;
}
Create Thymeleaf Template
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Add CSS and JS to Thymeleaf</title>
<link th:href="@{/css/main.css}" rel="stylesheet" />
<script type="text/javascript" th:src="@{/js/actions.js}"></script>
</head>
<body>
<h2>Style Heading H2</h2>
<p>
This is text on which we want to apply <strong>very special</strong> styling.
</p>
<button type="button" th:onclick="showAlert()">Show Alert</button>
</body>
</html>
3. Using JavaScript
function showAlert() {
alert("The button was clicked!");
}
<script type="text/javascript" th:src="@{/js/demo.js}"></script>
<button type="button" th:onclick="demo()">Show Alert</button>
Related Thymeleaf Tutorials and Examples
- Introducing Thymeleaf | Thymeleaf Template | Thymeleaf Template Engine
- Thymeleaf Example with Spring Boot
- How to Add CSS and JS to Thymeleaf
- Add Bootstrap CSS to Thymeleaf
- How to handle null values in Thymeleaf?
- How to Loop a List by Index in Thymeleaf
- Thymeleaf Array Example - Array Index, Array Iteration
- Thymeleaf Enums Example
- Thymeleaf If Else Condition Example
- Thymeleaf Switch Case Example
Comments
Post a Comment
Leave Comment