BorisMoore / jsrender

A lightweight, powerful and highly extensible templating engine. In the browser or on Node.js, with or without jQuery.
http://www.jsviews.com
MIT License
2.67k stars 339 forks source link

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

Closed isatrio closed 6 years ago

isatrio commented 6 years ago

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?

Paul-Martin commented 6 years ago

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

{{for audios}}
  {{for datas}}
    {{:name}}
  {{/for}}
  {{:url}}
{{/for}}
BorisMoore commented 6 years ago

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}}
BorisMoore commented 6 years ago

Closing this - since the question is answered.