1

this is the model I pass to my handlebars template

module.exports = function(showHeader, userId){ // the data model
  return {
    userId: userId,
    seminars: userSeminars;
  };
};

var userSeminars = [{ // some information
    seminarId: 1,
    isRated: true
}, {
    seminarId: 2,
    isRated: false
}];

and when rendering my template I use this HTML code

{{#each seminars}}
    <div class="seminarContainer">

        {{#if isRated}}
            <button onclick="loadStatistics({{seminarId}}, {{userId}})">Do Something 1</button>
        {{else}}
            <button onclick="loadQuestionnaire({{seminarId}})">Do Something 2</button>
        {{/if}}
    </div>
{{/each}}

but when debugging, {{userId}} is undefined. I went for this test routine and write it above the each-loop

$(document).ready(function () {
   alert({{userId}}); // this works
});

userId is not undefined. But when iterating over the array it is undefined. How can I leave the array scope within the loop? I would have to access the data model object, not an attribute in the array.


EDIT

Access a variable outside the scope of a Handlebars.js each loop

When I want to leave the scope I can use {{../userId}}

Within the loop

<p>{{../userId}}</p>

works fine but when using this for parameters like

onclick="loadStatistics({{seminarId}}, {{../userId}})"

the second parameter is undefined.

Question3r
  • 2,166
  • 19
  • 100
  • 200

1 Answers1

1

After a quick search I found this:

Access a variable outside the scope of a Handlebars.js each loop

I'll sum it up, there's an option given by handlebars to use the ../ syntax to make a reference to the parent scope.

So for example:

<button onclick="loadStatistics({{seminarId}}, {{../userId}})">Do Something 1</button>


EDIT:

With further looking I also found this answer to a similar question. Apparently, because you went another level up in the scope chain when you declared an #if, you then need to take that into consideration as well.

{{#if isRated}}
    <button onclick="loadStatistics({{seminarId}}, {{../../userId}})">Do Something 1</button>
{{else}}
    <button onclick="loadQuestionnaire({{seminarId}})">Do Something 2</button>
{{/if}}
fingeron
  • 1,152
  • 1
  • 9
  • 20
  • hm yes, this is a good start but when passing in parameters `onclick="loadStatistics({{seminarId}}, {{../userId}})"` it is still undefined. When writing `

    {{../userId}}

    ` it works
    – Question3r Dec 26 '17 at 19:40
  • I edited my answer, please try it and let me know how it went. – fingeron Dec 26 '17 at 19:45