Forum Discussion

yurikleban's avatar
9 years ago

Target a user's role via freemarker

Hey folks,

 

Wanted to see if anyone ever implemented something similar: 

 

We learned how to target anonymous users with the following syntax:

<#if user.anonymous == true>
User is anonymous. Display anonymous message here.
<#else>
User is authenticated. Display authenticted message here. You <em>can</em> <u>also</u> <strong>use</strong> HTML!
</#if>

However, I was wondering if someone could share the syntax to target multiple user roles, e.g.:

<#if user.role == Admin | Author | LithiumAuthor>
User has a role of admin or author or lithiumauthor and thus should see this
<#else>
if they do not have that role, they should see this
</#if>

 

Thanks for any insights,

Y

  • yurikleban - Sure, try this.

     

    <#attempt>
    	<#assign user_has_role = false />
    	<#if user.registered >
    		<#list restadmin("/users/id/${user.id?c}/roles").roles.role as role>
    			<#if role.name?? && (role.name == "Role1" || role.name == "Role2" || role.name == "Role3")>
    				<#assign user_has_role = true />
    			</#if>
    		</#list>
    	</#if>
    	<#if user_has_role >
    		Content will go here
    	</#if>
    <#recover>	
    	<!-- Something bad happened -->
    </#attempt>	

     

    I hope this helps.

    • ChiaraS's avatar
      ChiaraS
      Lithium Alumni (Retired)

      You can also use REST v2 for that:

       

      <#function user_has_role (id, roles)>
        <#assign liql = "SELECT id FROM users WHERE roles.name IN (${roles}) and id = '${id}'" />
        <#assign query = rest("2.0","/search?q=" + liql?url) />
        <#if (query.status == "success") && query.data.size gt 0>
        	<#return true>
        <#else>
          <#return false>
        </#if>
      </#function>

      and call it like this:

      <#if user.registered && user_has_role(user.id,"'Administrator', 'Lithium'")>
      ...
      </#if>