1. Introduction

In this quick tutorial, we’re going to learn how to use CSS and JavaScript in our Thymeleaf templates.

First, we’ll go over the expected folder structure so we know where to put our files. After that, we’ll see what we need to do to access those files from a Thymeleaf template.

We’ll start by adding CSS styling to our page and then move on to adding some JavaScript functionality.

2. Setup

In order to use Thymeleaf in our application, let’s add the Spring Boot Starter for Thymeleaf to our Maven configuration:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

3. Basic Example

3.1. Directory Structure

Now, as a reminder, Thymeleaf is a templating library that can be easily integrated with Spring Boot applications. By default, Thymeleaf expects us to place those templates in the src/main/resources/templates folder. We can create subfolders, so we’ll be using a subfolder called cssandjs for this example.

For CSS and JavaScript files, the default directory is src/main/resources/static. Let’s create static/styles/cssandjs and static/js/cssandjs folders for our CSS and JS files, respectively.

3.2. Adding CSS

Let’s create a simple CSS file named main.css in our static/styles/cssandjs folder and define some basic styling:

h2 {
    font-family: sans-serif;
    font-size: 1.5em;
    text-transform: uppercase;
}

strong {
    font-weight: 700;
    background-color: yellow;
}

p {
    font-family: sans-serif;
}

Next, let’s create a Thymeleaf template named styledPage.html in our templates/cssandjs folder to use these styles:

<!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="@{/styles/cssandjs/main.css}" rel="stylesheet" />
</head>
<body>
    <h2>Carefully Styled Heading</h2>
    <p>
        This is text on which we want to apply <strong>very special</strong> styling.
    </p>
</body>
</html>

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. The @{/styles/cssandjs/main.css} syntax is Thymeleaf’s way of doing URL linking.

If we run our application, we’ll see that our styles have been applied:

BAEL-3827

3.3. Using JavaScript

Next, we’re going to learn how to add a JavaScript file to our Thymeleaf page.

Let’s begin by adding some JavaScript to a file in src/main/resources/static/js/cssandjs/actions.js:

function showAlert() {
    alert("The button was clicked!");
}

Then we hop back over to our Thymeleaf template and add a