Search code examples
view-helpersjsrenderjsviews

JsViews/JsRender temporary/contextual helper variable in for loop


I'm trying to store a temporary/contextual variable in a for loop for later use inside another for loop. I used http://borismoore.github.io/jsrender/demos/step-by-step/11_accessing-parent-data.html as a reference.

{^{for instances ~templateId=templateId}}
    {{:~templateId}}
    <select data-link="templateId" class="selected-visible" name="select-template">
        {^{for ~root.templates}}
            <option data-link="{:name} value{:id} selected{:id == ~templateId}"></option>
        {{/for}}
    </select>
{{/for}}

Each data object in the instances array has a templateId property that is set to a certain value and each object in the templates array has an id property.

The first problem is that my debug {{:~templateId}} is not showing up. It seems the variable is not assigned.

After only using the ~helper set within the template markup, I have tried explicitly defining the helper in my "viewmodel" with

$.views.helpers({templateId: 0});

Now the value gets printed when I do not set it in the for loop, but when I set it in the for loop it disappears again.

The next problem might be that the ~templateId helper is not available in a ~root-scoped for loop, because the helper should only be available in child views of the instances loop?

The ultimate goal is to select the correct value in the select, so if other solutions are available, please do tell.


Solution

  • You need to remove ~templateId=templateId from your template...

    Explanation:

    The syntax ~helper is used to access helpers/contextual parameters, which can be either be passed in/registered externally, as shown here http://www.jsviews.com/#helpers, or can be created/set within a template, as in the example you linked to {{for movies ~theater=theater}} , or in this one: ~frstNm=firstName: http://www.jsviews.com/#samples/jsr/paths.

    So generally you will either pass a helper in, or create it within the template - not both.

    In your example above you are first passing ~templateId in - as 0 - and then you are redefining it as a contextual parameter, using ~templateId=templateId (which is actually setting its value to undefined, since ...=templateId sets it to the value of the templateId property of the current data - undefined, in your case).