jsRender loop a List<string>
Asked Answered
R

4

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.

Realgar answered 6/8, 2012 at 13:44 Comment(0)
A
11

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

Autography answered 6/8, 2012 at 16:7 Comment(4)
just out of curiosity, is this a documented method?Marceline
@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")Deason
need an example in contextCeltuce
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.Autography
C
20
{{#data}}

Didn't work for me.

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

{{>#data}}
Cardoza answered 22/8, 2012 at 14:3 Comment(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/#htmltagCeltuce
A
11

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

Autography answered 6/8, 2012 at 16:7 Comment(4)
just out of curiosity, is this a documented method?Marceline
@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")Deason
need an example in contextCeltuce
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.Autography
C
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 >

Celtuce answered 8/3, 2017 at 22:57 Comment(0)
H
0

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

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

in the script.

Homeopathic answered 22/7, 2016 at 4:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.