How to use javascript in Thymeleaf?

Thymeleaf is a Java-based template engine that is often used in conjunction with Spring Framework for building web applications. If you want to use JavaScript within a Thymeleaf template, you can do so by embedding JavaScript code directly in your HTML templates. Here’s a step-by-step guide with code examples:

  1. Create a Thymeleaf HTML Template:
    Start by creating an HTML template file with thetechreader.html extension. You can place this file in your web application’s resources/templates directory.
//techreader.html   

<!DOCTYPE html>
   <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
   <head>
       <title>Tech Reader with JavaScript</title>
   </head>
   <body>
       <h1>Using JavaScript in Thymeleaf</h1>

       <!-- Add your JavaScript code here -->
       <script type="text/javascript">
           function showMessage() {
               var message = "Hello, Tech Reader!";
               alert(message);
           }
       </script>

       <!-- Call the JavaScript function -->
       <button onclick="showMessage()">Click me</button>
   </body>
   </html>
  1. Include Thymeleaf Dependency:
    Make sure your project has Thymeleaf as a dependency in your build configuration (e.g., Maven or Gradle). For Maven, add this dependency to your pom.xml:
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-thymeleaf</artifactId>
   </dependency>
  1. Configure Spring Boot:
    If you’re using Spring Boot, you typically don’t need any additional configuration for Thymeleaf as long as your templates are in the correct location (usually in the resources/templates directory).
  2. Run Your Application:
    Start your Spring Boot application.
  3. Access Your Page:
    Open a web browser and navigate to the URL where your Thymeleaf template is served (e.g., http://localhost:8080/techreader).

You’ll see the “Using JavaScript in Thymeleaf” page with a button that, when clicked, triggers the JavaScript function showMessage(), which displays an alert box with the message “Hello, Thymeleaf!”.

Remember to adapt the template and JavaScript code according to your specific requirements. Thymeleaf provides powerful features for integrating dynamic data from your Java backend into your templates, so you can combine JavaScript with server-generated content seamlessly.

Leave a Comment