ONDoubleB
ONDoubleB

Reputation: 330

JsRender, how to render an anonymous array?

I have an anonymous array being passed into a JsRender template, how do I refer to each element to render them dynamically?

Here is the template code, I have it all set up, I just don't know what variable to pass into the {{for}} tag:

<script id="template" type="text/x-jsrender">
    {{for /*What goes here?*/}}
        <div id="{{>id}}" class="title">{{>title}}</div>
    {{/for}}
</script>

Here is the code to render the template with the data. I don't know the length of the array being passed into the method.

$('#template').render([{
    id: 1,
    title: 'first title'
}, {
    id: 2,
    title: 'second title'
}, {
    id: 3,
    title: 'third title'
}]);

Upvotes: 0

Views: 683

Answers (2)

BorisMoore
BorisMoore

Reputation: 8524

If you are passing an array to the JsRender method, then JsRender will automatically iterate over the array, and concatenate the result of applying the template to each item in the array.

http://www.jsviews.com/#tmplrender

So you don't need to wrap in {{for ...}}. Just write:

<script id="template" type="text/x-jsrender">
    <div id="{{>id}}" class="title">{{>title}}</div>
</script>

Incidentally you can tell render NOT to render arrays automatically, by passing true as second parameter: $('#template').render(myArray, true). Now in that case you would need to tell the template itself to iterate - which you can do by wrapping in either {{for}}<div>...</div>{{/for}} (with no parameter) - or, equivalently {{for #data}}<div>...</div>{{/for}} (#data as parameter).

Upvotes: 1

ONDoubleB
ONDoubleB

Reputation: 330

After some research and initiative I worked out that #data represents the current value in JsRender.

Therefore {{for #data}} is the correct answer!

Upvotes: 0

Related Questions