Search code examples
spring-bootspring-securitythymeleaf

hasRole check doesnt work with th:replace


I am having trouble getting a th:replace to work this is my thymeleaf:

<div th:replace="${#authorization.expression('hasRole(''ROLE'')') ? 'fragments/first :: content(content=${content})' : 'fragments/second :: content(content=${content})'}"></div>

If I go to this page I get this error:

Error resolving template [${#authorization.expression('hasRole(''ROLE'')') ? 'fragments/upgradeblock], template might not exist or might not be accessible by any of the configured Template Resolvers (template: "fragments/first" - line 36, col 34)

I think I have to change something in the Thymeleaf code but cant find out what. Thank you for your help


Solution

  • Seems like the correct syntax for this should look like:

    <div th:replace="${#authorization.expression('hasRole(''ROLE'')')} ? ~{fragments/first :: content(content=${content})} : ~{fragments/second :: content(content=${content})}"></div>
    

    Even further, this syntax worked for me as well:

    <div th:replace="~{${'fragments/' + (#authorization.expression('hasRole(''ROLE'')') ? 'first' : 'second')} :: content(content=${content})}"></div>