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:
In JavaScript blocks, we can initialize variables with values transferred from Java objects. The following examples shows how to set JS variables in Thymeleaf:
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:
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.
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}