1. Problem
In this short Q&A article, we are going to show how to get URL request parameters in Thymeleaf template view.
2. Solution
Luckily, request parameters can be easily accessed in Thymeleaf views using built-in tools.
For request parameters like in the following URL:
https://frontbackend.com/search?query=Thymeleaf
In order to access query
parameter we could use the param
object:
<div th:if="${(param.query != null) and (param.query[0] == 'Thymeleaf')}">
Thymeleaf is awesome
</div>
Another way to access URL parameters is by using the special #request
object that gives you direct access to the javax.servlet.http.HttpServletRequest
class:
<div th:if="${#request.getParameter('query') != null and #request.getParameter('query') == 'Thymeleaf'}">
Thymeleaf is awesome
</div>
Note that parameters could be multivalued like in the following example:
https://frontbackend.com/search?query=Thymeleaf&query=Templates
In this case we need to use an index of the array:
<p th:text="${param.query[0] + ' ' + param.query[1]}" th:unless="${param.query == null}">Test</p>
To iterate over array we could use th:each
attribute.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}