Monday, April 30, 2018

How to iterate over a List or Map Object in Thymeleaf (With Examples)?

Although Thymeleaf provides an easy way to iterate over List or Map objects but if one doesn't know the exact syntax for iteration then it could be tricky and one might get surprising results. Today we would discuss how to iterate over a List or Map object in Thymeleaf using th:each attribute.


Table Of Content
1. Introduction
2. Iterate Over List Object
3. Iterate Over Map Object
4. Keeping Iteration Status
5. Conclusion

Friday, April 20, 2018

How to construct dynamic URL using Thymeleaf

While creating a web application, it's very common to sends parameters in the request as query string or as the path variables. Recently, I have tried to achieve the same using Thymeleaf but faced some problem because I was new to Thymeleaf. But later found that Thymeleaf provides very simple and straightforward way to create dynamic URLs. Today we would see How? As it could be useful to anyone who would come across the same problem.

We would be using link expressions, a type of Thymeleaf Standard Epression: @{...} to create URLs in our web application.
  1. Passing parameters as Query String
    O/P : <a href="/orderdetails?id=3">
    <a th:href="@{/orderdetails(id=3)}"> 
    <a th:href="@{/orderdetails(id=${order.id})}" th:text="${order.id}">Order ID</a>
    
    Would like to pass several parameters,
    O/P: <a href="/orderdetails?id=3&amp;action=show_all">
    <a th:href="@{/orderdetails(id=3,action='show_all')}">
    
  2. Passing parameters as Path Variables
    O/P : <a href="/orderdetails/3">
    <a th:href="@{/orderdetails/{id}(id=3)}"> 
    <a th:href="@{/orderdetails/{id}(id=${order.id})}" th:text="${order.id}">Order ID</a>
    
    Alternative way:
    <a th:with="id=${order.id}" th:href="@{${'/orderdetails/' + id}}" th:text="${id}">Order ID</a>
    <a th:href="@{${'/orderdetails/' + order.id}}" th:text="${order.id}">Order ID</a>
If you would like to know about how to fetch the data [passed as Query String or as Path Variable using Thymeleaf] from incoming request in your Controller in Sprig MVC then you could checkout my post that describes the Differences between @RequestParam and @PathVariable annotations in Spring MVC? Happy Learning!!