Sam
Sam

Reputation: 57

Iterating over array returned from HandlebarsHelper

I have two properties in my HBS file. One is a users authorized roles, the 2nd is all the roles available in the database. I send the roles from both to a HBS helper and compare them, if the user has the roles (in the value parameter) I add them to a new array called roleArray, if the user doesn't have the role I add them to the roleArray from the roles in the database array (option parameter).

I don't know how to iterate of the array when it is returned.

file.hbs

{{selected properties.roles properties.user.roles ../stateSelected}}

express-setup.js

hbs.registerHelper('selected', function(option, value){

    var i;
    var j;
    var roleName;
    var userRole;
    var roleArray = [];

    //Roles the user has
    for(i = 0; i < value.length; i++){
        userRole = value[i].rolename;
        roleArray.push(userRole);
    }

    //Roles in the database
    for(j = 0; j < option.length; j++){
        roleName = option[j].rolename;

        if(roleArray.includes(roleName)){
            //Nothing happens
      }else  {
            roleArray.push(roleName);
       }
    }
    return roleArray;     
 });

So what I want to do is iterate through the returned roleArray on the front end and display them. Eventually the helper will return an array of objects including a selected property so that I can show toggle buttons on or off based on if the user has the role or not, but for now just displaying them would be good.

Thanks.

Upvotes: 1

Views: 45

Answers (1)

slebetman
slebetman

Reputation: 114014

If your version of handlebars support subexpressions then just do:

{{#each (selected properties.roles properties.user.roles ../stateSelected)}}
    do stuff here
{{/each}}

if not then there is a subexpression helper available on npm that uses the same syntax.

Upvotes: 2

Related Questions