th:each on roles

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

th:each on roles

bigal.nz
Hi All,

This question relates to testing a users role, against a array of roles, and more than one role.

ie a user might be ADMIN and CMF and a particular page or element may be displayed for more than one role.

So far I have it working for one role:

th:if="${user.roles[0].role}=='CMF'"

but it really needs to be tested against every role in the array - how to do this?

And it needs to be test against more than one role like:

th:if="${user.roles[0].role}=='CMF' OR 'ADMIN'"

Thanks

Al
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: th:each on roles

Metroids
Add a method on your User object that checks if they have any of the roles:

        public boolean hasAny(String... rolesToTest) {
            ...
            ...
        }

And then you can use that in your thymeleaf for all tests...

th:if="${user.hasAny('CMF')}"

or

th:if="${user.hasAny('CMF', 'ADMIN')}"
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: th:each on roles

bigal.nz
I was thinking more like something:

div th:if="${#arrays.contains(user.roles, 'role=Admin')}" class="col-xs-1">Hello</div>

My object looks like



But this html isnt working at the moment? I had it working with user.roles[0].role='Admin' so perhaps for the contains statement it needs to reference the extra "role" on the end?
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: th:each on roles

Metroids
#arrays.contains doesn't work that way.

This: ${#arrays.contains(user.roles, 'role=Admin')}

is trying to compare the a String "role=Admin" to a Role object (which will never work).

This: ${user.roles[0].role}=='CMF'}

works because you compare the string 'CMF' to another string.


Loading...