Search code examples
jqueryjquery-templates

parent loop's itemNumber value in jQuery jsrender.js & jquery.views.js


I have using jQuery template using jsrender.js & jquery.views.js by http://github.com/BorisMoore/jsviews

I have 1 nested loop and inside teh nested loop i want the get itemNumber or some other value. Eg:

Template:

{{#each ImageQuestions}}
  <div id="image-{{=$view.itemNumber}}">
  {{#each GroupImagesRepeatation}}
    <input type="radio" name="{{=$view.parent.data.QuestionID}}" value="{{=$view.itemNumber}}" />
  {{/each}}
{{/each}}

Array:

var Questions = {
        ImageQuestions: [
                            { 
                                QuestionID: 1,
                                GroupImagesRepeatation: [1, 2, 3, 4]
                            },
                            {
                                QuestionID: 2,
                                GroupImagesRepeatation: [1, 2, 3, 4, 5, 6]
                            }
                        ]
    };

Query: {{=$view.parent.data.QuestionID}} is what i want to work correctly. I require to give unique name to radioList for each nested loop.

Please assist me.


Solution

  • The reason {{=$view.parent.data.QuestionID}} is not returning the correct value is because you need to step up through two parent levels: {{=$view.parent.parent.data.QuestionID}}. The immediate parent has as data the GroupImagesRepeatation array. Its parent is the data item of the outer each loop - which has a questionID property.

    You can use a more compact syntax:

    {{#each ImageQuestions}}
      <div id="image-{{=$itemNumber}}">
        {{#each GroupImagesRepeatation}}
          <input type="radio" name="{{=$parent.parent.data.QuestionID}}" value="  {{=$itemNumber}}" />
        {{/each}}
    {{/each}}
    

    A tip - for debugging within the compiled template: Set $.views.allowCode = true; and then add {{*debugger;}} within the template, e.g. {{*debugger;}}<input type="radio" ....