10

A question on the {{for}} loop in jsRender.

The demo shows we can loop through a collection of complex objects and display their properties:

{{for languages}}
    <div>
        <em>{{>name}}</em>
    </div>
{{/for}}

But what if my languages is only a List<string>? There will be no {{>name}} to be displayed. How can we reference the individual string values?

Thanks.

4 Answers 4

20
{{#data}}

Didn't work for me.

Something seems to have been changed, this is what did it for me:

{{>#data}}
1
  • @r2b2s - actually it's the exact opposite. "The {{> ...}} tag should be used instead of the {{: ...}} whenever data being rendered is not fully trusted – in order to protect against HTML injection attacks." - jsviews.com/#htmltag
    – Sergey
    Mar 8, 2017 at 22:39
11

You should be able to use #data to access the individual string values inside the loop.

4
  • just out of curiosity, is this a documented method? Dec 16, 2015 at 4:21
  • @mattlohkamp There's a mention of it here ("#data is short for #view.data") and here ("a view has a data property, which is the current data context used for rendering that view")
    – Frank Tan
    Nov 4, 2016 at 20:18
  • need an example in context
    – Sergey
    Mar 8, 2017 at 22:31
  • This is a very old answer and while it was correct at the time it's entirely possible that it's not relevant to recent versions of jsRender. I haven't used jsRender for several years and have not kept up with their changes.
    – MrOBrian
    Mar 14, 2017 at 17:21
7

You should use:

{{>#data}} or {{>}} - (encodes HTML)

{{:#data}} or {{:}} - (non HTML)

For example:

Let's say your languages object looks like this:

var languages = ['en', 'sp', 'zh'];

{{for languages}}
    <div>
        <em>{{>}}</em>
    </div>
{{/for}}

Will result in:

<div>
   <em>en</em>
</div>
<div>
   <em>sp</em>
</div>
<div>
   <em>zh</em>
</div>

Documentation

#data

Difference between : and >

0

Also, if you want to do some comparisons, you can use code like:

{{if #data == 'xxx' || #data == 'yyy'}}
...
{{/if}}

in the script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.