Home > AI > Backend > SpringBoot > spring-boot-starter-thymeleaf >

add css and js to thymeleaf

CSS

the css file is put under static folder, and you use this line to include that css

<link rel="stylesheet" th:href="@{/css/good.css}" />

JS

Same as CSS, files are put under static directory and use this line to include it.

<script type="text/javascript" th:src="@{/js/good.js}" ></script>

Example

emplates/good.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Add CSS and JS to Thymeleaf</title>


    <link rel="stylesheet" th:href="@{/css/good.css}" />
    <script type="text/javascript" th:src="@{/js/good.js}" ></script>

</head>
<body>
<h2>Carefully Styled Heading</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>
<!-- We've created a local JavaScript variable
that contains the name model value from our controller
that we can then use in our JavaScript on the rest of the page.-->
<script th:inline="javascript">
    var nameJs = /*[[${name}]]*/;
</script>
<button type="button" th:onclick="showName(nameJs);">Show Name</button>

</body>
</html>

static/css/good.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;
}

static/js/good.js

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



function showName(name) {
    alert("Here's the name: " + name);
}

Demo12Application.java

@SpringBootApplication
@Controller
public class Demo12Application  {
	public static void main(String[] args) {

        SpringApplication.run(Demo12Application.class, args);
	}



    @GetMapping("/good-second")
    public String getStyledPage(Model model) {
        model.addAttribute("name", "jobyme88");
        return "good";
    }

}

You can visit following urls


localhost:8081/css/good.css
localhost:8081/js/good.js
localhost:8081/good
localhost:8081/good-second

Leave a Reply