- Thymeleaf Javascript Inline Example with Variable
- Thymeleaf Javascript Inline th:inline=»javascript»
- Evaluate Java Bean with Thymeleaf Javascript Inline Expression
- Use Javascript Commented Code using Thymeleaf
- Remove Javascript Code using Thymeleaf
- Complete Example
- Output
- How set a JavaScript variable in Thymeleaf
- You might also like.
- How to set up a JavaScript variable from Spring model using Thymeleaf?
- 2. JavaScript inlining
- 3. Conclusion
Thymeleaf Javascript Inline Example with Variable
On this page we will learn using Thymeleaf Javascript inline with variable. Thymeleaf evaluates the expression and assigns the value to a variable. To enable it, we need to use th:inline=»javascript» as an attribute in
Thymeleaf Javascript Inline th:inline=»javascript»
Thymeleaf provides javascript mode using th:inline=»javascript». Find the syntax below. Here Thymeleaf fetches user name from Servlet session in our example.
1. /*[[. ]]*/ syntax evaluates contained expression.
2. When page statically runs, the commented part does not run. So Thymeleaf expression is ignored and does not display when it runs statically and only code after inline expression is executed.
3. After execution, Thymeleaf removes all the code after inline expression.
The output of the above code will be as follows.
Evaluate Java Bean with Thymeleaf Javascript Inline Expression
If we have a bean with some attributes and we want to assign it to Javascript variable then we can do as follows.
null will be assigned to those attributes of bean which has been set no value.
Find the output of the above code snippet.
Use Javascript Commented Code using Thymeleaf
With Thymeleaf we can add Javascript commented code in our running code using /*[+ . +]*/ syntax. Find the javascript template for a variable.
/*[+ var extraMsg = 'Thymeleaf javascript example.'; +]*/
var extraMsg = 'Thymeleaf javascript example.';
If we want to concatenate some value with the result of Javascript inline expression, we do as follows.
var msg = 'My village name, ' + 'Dhananjaypur';
Remove Javascript Code using Thymeleaf
Without commenting Javascript code, we can remove it from running code using Thymeleaf /*[- */ . /* -]*/ syntax. Find the sample code.
/*[- */ var data = 'This is a non-working data.'; /* -]*/
Complete Example
package com.concretepage; import org.thymeleaf.TemplateEngine; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; public class ThymeleafAppUtil < private static TemplateEngine templateEngine; static < ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); templateResolver.setTemplateMode("XHTML"); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setCacheTTLMs(3600000L); templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); >public static TemplateEngine getTemplateEngine() < return templateEngine; >>
package com.concretepage; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.thymeleaf.context.WebContext; public class WelcomeApplication < public void process(HttpServletRequest request, HttpServletResponse response) throws IOException < WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale()); ThymeleafAppUtil.getTemplateEngine().process("welcome", ctx, response.getWriter()); >>
package com.concretepage; public class Address < private String villageName; private String post; private String district; private String state; public String getVillageName() < return villageName; >public void setVillageName(String villageName) < this.villageName = villageName; >public String getPost() < return post; >public void setPost(String post) < this.post = post; >public String getDistrict() < return district; >public void setDistrict(String district) < this.district = district; >public String getState() < return state; >public void setState(String state) < this.state = state; >>
package com.concretepage; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet(urlPatterns = "/welcome", loadOnStartup = 1) public class WelcomeServlet extends HttpServlet < private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException< doGet(request,response); >public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException < response.setContentType("text/html;charset=UTF-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); Address address = new Address(); address.setVillageName("Dhananjaypur"); address.setDistrict("Varanasi"); address.setState("UP"); HttpSession session = request.getSession(); session.setAttribute("userName", "Mahesh Sharma"); session.setAttribute("address", address); WelcomeApplication application = new WelcomeApplication(); application.process(request, response); >>
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf Javascript Demo</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script th:inline="javascript"> /*<![CDATA[*/ var user = /*[[$]]*/ 'User Name'; var address = /*[[$]]*/ null; /*[+ var extraMsg = 'Thymeleaf javascript example.'; +]*/ /*[+ var msg = 'My village name, ' + [[$]]; +]*/ /*[- */ var data = 'This is a non-working data.'; /* -]*/ /*]]>*/ </script> </head> <body> <p th:text="$">User Name</p> </body> </html>
Output
Run the code using URL http://localhost:8080/concretepage-1/welcome and then check the view source. It will be as given below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Thymeleaf Javascript Demo</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script> /*<![CDATA[*/ var user = 'Mahesh Sharma'; var address = ; var extraMsg = 'Thymeleaf javascript example.'; var msg = 'My village name, ' + 'Dhananjaypur'; /*]]>*/ </script> </head> <body> <p>Mahesh Sharma</p> </body> </html>
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:
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 in Thymeleaf templates allows us to process the JavaScript 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>
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 = john@example.com;
Uncaught SyntaxError: Invalid or unexpected token
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 = /*[[$]]*/ "John Deo"; var email = /*[[$]]*/ "john@example.com"; var age = /*[[$]]*/ 25; var createdAt = /*[[$]]*/ "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.
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. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
How to set up a JavaScript variable from Spring model using Thymeleaf?
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 $ has value 5 and $ 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.