Jsrender if-else using {{= propName}}

I am trying to execute jsRender.

What I want to do:

JS Template:

<script id="theaterTemplate" type="text/x-jquery-tmpl">
    {{* 
        if ("{{=theaterId}}" == getCurrentTheaterId()) {
    }}
        <a class="active" href="#">
    {{*
        } else {
    }}         
        <a href="#">           
    {{* } }}
        {{=theaterName}}
    </a>
</script>

In other JS:

function getCurrentTheaterId() {
    return "523";
}

Basically, in the template, if the current tester identifier in the iteration matches what is returned from the js function, set the class to active. "{{= TheaterId}}" breaks in the if condition. I think you are not allowed access to the current json properties in the if condition.

Any ideas on how to do this?

Hope this makes sense. Thank!

+5
source share
2 answers

In their sample program, they have the following:

$.views.allowCode = true;/

http://borismoore.github.com/jsrender/demos/step-by-step/11_allow-code.html

[change]

You must tell jsRender about the external function. Here is a working example:

   <script type="text/javascript">
        function IsSpecialYear()
        {
             return '1998';
        }

        // tell jsRender about our function
        $.views.registerHelpers({ HlpIsSpecialYear: IsSpecialYear });

    </script>

    <script id="movieTemplate" type= "text/html">

        {{#if ReleaseYear == $ctx.HlpIsSpecialYear() }}
            <div style="background-color:Blue;">
        {{else}}
            <div>
        {{/if}}   
            {{=$itemNumber}}: <b>{{=Name}}</b> ({{=ReleaseYear}})
        </div>

    </script>

    <div id="movieList"></div>

<script type="text/javascript">

    var movies = [
        { Name: "The Red Violin", ReleaseYear: "1998" },
        { Name: "Eyes Wide Shut", ReleaseYear: "1999" },
        { Name: "The Inheritance", ReleaseYear: "1976" }
    ];

    $.views.allowCode = true;

    $("#movieList").html(
        $("#movieTemplate").render(movies)
    );

</script>   

[EDIT 2] A more complex logical condition:

    function IsSpecialYear(Year, Index)
    {
        if ((Year == '1998') && (Index == 1))
            return true;
        else
            return false;
    }

    // tell jsRender about our function
    $.views.registerHelpers({ HlpIsSpecialYear: IsSpecialYear });

</script>

<script id="movieTemplate" type= "text/html">

{{#if $ctx.HlpIsSpecialYear(ReleaseYear, $itemNumber)  }}
    <div style="background-color:Blue;">
{{else}}
    <div>
{{/if}}
+6

All Articles