BorisMoore / jsrender

A lightweight, powerful and highly extensible templating engine. In the browser or on Node.js, with or without jQuery.

Home Page:http://www.jsviews.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can't call another root object on loop "for"

isatrio opened this issue · comments

The object look like below

{
audio: {
datas:[{name: "test"}, {name: "test 2"}]
url: 'http://someurl.com'
}

The template look like below

<script id="audioTemplate" type="text/x-jsrender">
  {{for audios.datas}}
    {{:name}}
    {{:audios.url}}
  {{/for}}
</script>

The audios.url can't show in the loop, the error is like "Uncaught TypeError: Cannot read property 'url' of undefined". Do you have suggestion for doing this?

url is a property of audio, whereas the context in the loop is audio.datas.
Try

{{for audios}}
  {{for datas}}
    {{:name}}
  {{/for}}
  {{:url}}
{{/for}}

Paul's approach is fine as long as you don't need to mix the two levels - as in:

name
url
name

If you do, then take a look at Accessing parent data for alternatives, such as:

{{for audio.datas ~url=audio.url}}
  {{:name}}
  {{:~url}}
  {{:name}}
{{/for}}

or

{{for audio.datas ~audio=audio}}
  {{:name}}
  {{:~audio.url}}
  {{:name}}
{{/for}}

Closing this - since the question is answered.