Search code examples
javascriptmeteorspacebars

Use a variable as name to access nested elements of another array


I do a each-loop for an array which I build in a helper:

Template.article.helpers({
    section: function() {
        return [
            {type: 'cars', sectionTitle: 'Cars'}, 
            {type: 'vegetables', sectionTitle: 'Vegetables'}
        ];
    },
});

The data for the articles comes from the router:

Router.route('/article/:_id', {
    name: 'article',
    data: function() {
        return {
            article: Articles.findOne({ _id: this.params._id })
        }
    }   
});

But now I want to access a subelement of article with the type of the helper. So in this example the each loop will be done two times: I first want to use ../article.cars and then ../article.vegetable. I hope you understand my problem. I want to get the name of the subelement by the helper type:

<template name="article">
    {{#each section}}
        <h1>{{this.sectionTitle}}</h1>

        <ul>
        {{#each ../article.type}} <!-- should get '../article.cars' and '../article.vegetable' -->
            <li>{{this.title}}</li>
        {{/each}}
        </ul>
    {{/each}}
</template>

I want to use the content of type as a variable name. If type is 'cars', then I want to use ../articles.cars'. Which would be something likearticles['cars']which would result ofarticles[type]. But in meteor this writing is not possible. Andarticles.type` is something different.


Solution

  • Just use another helper:

    s: function(article) {
        return article[this.type];
    }
    

    And send a argument with your spacebar:

    {{#each s ../article}}