Search code examples
jsonhandlebars.js

Dynamic property lookup handlebars each loop


Can i have the property i want to loop through come from my data?

{{#each (lookup . 'reference')}}
    <li>{{this.text}}</li>
{{/each}}

Doesn't seem to work, just wondering if this someone else has done this in the past?


Solution

  • Couldn't find an existing way of doing it so i created a custom each helper that does the job. To avoid any confusion i'm using precompiled grunt handlebars https://github.com/patrickkettner/grunt-compile-handlebars but the script should work with some slight modification in the invoking with addHandlebarHelper.

    Gist - https://gist.github.com/mikemellor11/9b23a0af217a3c67593c

    module.exports = function (path, context, option) {
        var ret = "";
    
        if(!option){
            option = context;
            context = option.data.root;
        }
    
        context = getProperty(path, context);
    
        for(var i=0, j=context.length; i<j; i++) {
            option.data.index = i;
            option.data.first = i === 0;
            option.data.last = i === (j - 1);
    
            ret = ret + option.fn(context[i]);
        }
    
        return ret;
    };
    
    
    function getProperty( propertyName, object ) {
        var parts = propertyName.split( "." ),
            length = parts.length,
            i,
            property = object || this;
    
        for ( i = 0; i < length; i++ ) {
            property = property[parts[i]];
        }
    
        return property;
    }