Search code examples
springtemplatesthymeleaf

Check if Thymeleaf template url contains string


How can I check if this URL 'http://localhost:8080/employees/subordinates/1' contains the string 'subordinates'? I'm trying to make the presence of an anchor conditional upon the URL containing the phrase. This is what I've been hoping to achieve.

<div th:if="${#strings.contains(#httpServletRequest.requestURI, 'subordinates')}">
    <a href="/employees/list">employee directory</a>
</div>

Solution

  • Yes, the workaround you mention in the comments is the way to do it.

    The #request, #response, #session, and #servletContext expression utility objects are no longer available in Thymeleaf 3.1. According to this issue:

    The #request, #response, #session and #servletContext expression utility objects should be removed from the Standard Dialect, both for security reasons (in order to avoid direct access to potentially unsafe properties such as request parameters) and also due to the fact that these are currently bound to the javax.* Servlet API, and generalizing the web interfaces in the Thymeleaf core in order to support jakarta.* and other web technologies would not be compatible with these specific objects still being available.

    The article Thymeleaf 3.1: What’s new and how to migrate recommends adding to your model, at the controller level, the specific pieces of information your templates need from these objects. For example, you can add the following to your controller:

    @ModelAttribute("requestURI")
    public String requestURI(final HttpServletRequest request) {
       return request.getRequestURI();
    }
    

    And use the attribute in your template this way:

    <div th:if="${#strings.contains(${requestURI}, 'subordinates')}">
        <a href="/employees/list">employee directory</a>
    </div>