Search code examples
javaspringspring-bootthymeleafmodelattribute

Using a value as an argument into another value in Thymeleaf


So lets say I have a @ModelAttribute of userCredentials which is a List<String> object.

and I have another ModelAttribute of type Map<String,String> of roles.

I can access them separately in HTML using Thymeleaf with:

${userCredentials.contains('<Hardcoded-value>')}

The problem i want the hardcoded value replaced and to use for example:

${userCredentials.contains('roles.client')}

Do you know how can i successfully use a model attribute as a parameter to the other model attribute. It works with the hardcoded values


Solution

  • You can use Thymeleaf pre-processing:

    ${userCredentials.contains(__${roles.get('client')}__)}
    

    Thymeleaf executes the preprocessing part in a first pass. So it will replace what is there with:

    ${userCredentials.contains(<result of roles.get() call here>)}
    

    And then execute the template rendering.