How to set a JavaScript variable in Thymeleaf

published: 11 Apr 2022

2 min read

How set a JavaScript variable in Thymeleaf

In this quick article, we will look at different ways of setting up a JavaScript variable by using Spring MVC Model object in a Thymeleaf template. If you need more information on how to use Thymeleaf with Spring Boot, take a look at this introductory tutorial.

Let us say we have the following Java model class named User.java for storing users data:

User.java

public class User implements Serializable {

    private String firstName;
    private String lastName;
    private String email;
    private int age;
    private Date created;

    // constructor, getters, and setters removed for brevity
}

And we have a controller method that creates a new User object and stores it in Spring MVC Model object:

@GetMapping('/')
public String homePage(Model model) {

    // create a new user object
    User user = new User('John', 'Doe', 'john@example.com',
            29, new Date());

    // store user object in 'Model' object
    model.addAttribute('user', user);

    return 'index';
}

JavaScript Inlining

JavaScript inlining in Thymeleaf templates allows us to process the JavaScript <script> blocks in HTML template mode. To use all features of HTML template mode in JavaScript blocks, you must enable JavaScript mode by explicitly specifying th:inline='javascript' attribute:

<script th:inline='javascript'>
    // write code here
</script>

Once the JavaScript mode is enabled, you can now use data from Spring MVC Model object to initialize JavaScript variables as shown below:

<script th:inline='javascript'>
    var name = [[${user.firstName + ' ' + user.lastName}]];
    var email = [[${user.email}]];
    var age = [[${user.age}]];
    var createdAt = [[${#dates.format(user.created, 'EEE, MMMM dd, yyyy')}]];
</script>

Thymeleaf template engine will process the above JavaScript block and will render the following JavaScript block in the final output:

<script>
    var name = 'John Doe';
    var email = 'john@example.com';
    var age = 29;
    var createdAt = 'Thu, January 30, 2020';
</script>

As you can see above, JavaScript inlining not only outputs the required text but also encloses it with quotes to output well-formed JavaScript literals. This happened because we output all expressions as escaped - using a double-bracket expression.

If you would have used unescaped expression like:

<script th:inline='javascript'>
    // ...
    var createdAt = [(${user.created.getTime()})];
</script>

The rendered block would look like the following:

<script>
    // ...
    var createdAt = 1580334577834;
</script>

Be careful while using an unescaped expression in JavaScript mode. You might end up generating a malformed JavaScript code. For example, if you use an unescaped expression for a string field like email:

var email = [(${user.email})];

It will render like:

var email = john@example.com;

And the browser will throw the following JavaScript error:

Uncaught SyntaxError: Invalid or unexpected token

JavaScript Natural Templates

JavaScript inlining is much more smarter than just applying JavaScript-specific escaping and outputting expression results as valid literals.

You can even specify default values for variables by wrapping the inline expressions in JavaScript comments like below:

<script th:inline='javascript'>
    var name = /*[[${user.firstName + ' ' + user.lastName}]]*/ 'John Deo';
    var email = /*[[${user.email}]]*/ 'john@example.com';
    var age = /*[[${user.age}]]*/ 25;
    var createdAt = /*[[${user.created}]]*/ 'January 29, 2020';
</script>

The above JavaScript inlining mechanism is especially useful for creating a quick prototype of a web page in the form of a static HTML file.

Thymeleaf will ignore everything we have written after the comments and before the semicolon. The static HTML file will have default values for all variables declared above. Since the Thymeleaf expressions are wrapped in comment blocks, the code will also be well-format.

This is what we call JavaScript natural templating! Thymeleaf is, in fact, a natural templating engine that works both in browsers and web applications.

Conclusion

That's all folks. In this short article, we looked at how to use the JavaScript inlining mechanism in Thymleaf templates. JavaScript inlining is a powerful feature that allows us to dynamically set the values of JavaScript variables using data from Spring MVC Model object in Thymeleaf.

JavaScript natural templating is another way of using JavaScript inlining while quickly crafting a static prototype of the website. If you want to learn more about getting started with Thymeleaf in Spring Boot, check out this guide.

How to set a JavaScript variable in Thymeleaf | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, static, programming
Check out what's on in the tag: javascript, static, programming, file