Question

I am trying to learn JSRender. Is it possible to render a sub template depending on a condition? Eg if #index = 1 or 2, render template A, if 3 or 4, render template B?

Was it helpful?

Solution

Here is the correct syntax - and some documentation links below.

<script id="tmplFeaturePanel1" type="text/x-jsrender">
    {{for List}}
        {{if #index == 1 || #index == 2}}
            {{include tmpl="#test1or2"/}}
        {{else #index === 3 || #index === 4 }}
            {{include tmpl="#test3or4"/}}
        {{else}}
            {{include tmpl="#testOther"/}}
        {{/if}}
    {{/for}}
</script>

or an even more compact syntax which works just the same is:

<script id="tmplFeaturePanel2" type="text/x-jsrender">
    {{for List}}
        {{if #index == 1 || #index == 2 tmpl="#test1or2"}}
        {{else #index === 3 || #index === 4 tmpl="#test3or4"/}}
        {{else tmpl="#testOther"/}}
        {{/if}}
    {{/for}}
</script>

where in both cases the referenced templates might be:

<script id="test1or2" type="text/x-jsrender">
    1or2 {{:name}}
</script>

<script id="test3or4" type="text/x-jsrender">
    3or4 {{:name}}
</script>

<script id="testOther" type="text/x-jsrender">
    Other: {{:name}}
</script>

See

BTW note that {{elseif ...}} or {{else if ...}} is NOT the correct syntax. In fact {{else someExpression}} works as an elseif. {{else}} works as an else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top