How to set up a JavaScript variable from Spring model using Thymeleaf?

January 04, 2020 No comments Thymeleaf Java Script Variable

1. Introduction

This article shows how to set up a JavaScript variable from Spring model in Thymeleaf template. We will present the best methods to transfer backend variable value into the JavaScript object using Thymeleaf.

2. JavaScript inlining

JavaScript inlining in Thymeleaf is used to integrate blocks of JavaScript code with the HTML template. In order to use all advanced Thymeleaf support mechanisms, JavaScript mode has to be enabled explicitly using th:inline="javascript" attribute:

<script th:inline="javascript">
   ...
</script>

In JavaScript blocks, we can initialize variables with values transferred from Java objects. The following examples shows how to set JS variables in Thymeleaf:

<script th:inline="javascript">
   var customerId = [[${customer.id}]];
   var customerName = [[${customer.name}]];
</script>

JavaScript inlining not only evaluates variables putted in double-bracket expressions but also enclose them with quotes and JavaScript-escape its contents.

For example when ${customer.id} has value 5 and ${customer.name} contains Example "Company" Name String, rendered block with customerId and customerName variables will look like the following:

<script>
    var customerId = 5;
    var customerName = 'Example "Company" Name';
</script>

JavaScript inlining is a smart mechanism that allows us to put default values for variables when preparing a prototype of the website and presenting a static HTML file.

<script th:inline="javascript">
   var customerId = /*[[${customer.id}]]*/ 5;
   var customerName = /*[[${customer.name}]]*/ "Example \"Company\" Name";
</script>

Thymeleaf, in the above example, will ignore everything we have written after the comment and before the semicolon. Static HTML file will have default values for customerId and customerName variables and because Thymeleaf expressions are putted in JavaScript comment blocks /* ... */ code will be also well-formed.

3. Conclusion

In this article, we showcased the best ways to set up a JavaScript variable from Spring model in Thymeleaf. Those who are creating dynamic websites using JavaScript and Spring Boot should find this post useful.

As usual, the code used in this article is available on our GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}