Search code examples
thymeleaf

Thymeleaf, how to delcare default values for variables?


For example, sortDir field is passed to model, but if I forget it, I want to use asc as default one.

This does not work as it shows div only when sortDir==null.

<div class="wrapper"
 th:if="${sortDir == null}" th:with="sortDir=${'asc'}">
// Main content
</div>

Solution

  • You should remove your conditional on the div and try to decide on the value with an inline expression as follows:

    <div class="wrapper" 
      th:with="sortDir=${sortDir != null} ? sortDir : 'asc'">
    // Main content
    </div>
    

    Another way to achieve this is by setting the value right in the controller before you return from the controller method. An example line might be as follows:

    @GetMapping
    public String getSomething(Model model) {
        if (sortDir == null) { sortDir = "asc" };
        model.addAttribute("sortDir", sortDir);
        return "someView";
    }