Trying to use allowCode in JsRender with {{* window.counter++ }} and test the result using boolean test

410 views Asked by At

I have the following template

    <script type="text/x-widget-template" id="genericRowValues">
        {{* window.counter = 0}}
        {{props}}
            {{* console.log(counter == 0)}}
            {{if counter == 0}}
                {{* console.log("WHY YOU NO WORK!")}}
                <div class="row">
            {{/if}}
            <div class="col-lg-4">
                <div class="input-group" style="margin-bottom:5px;">
                    <b>{{>key}}</b>
                    <div class="well well-sm">
                        {{>prop}}
                    </div>
                </div>
            </div>
            {{if counter == 4}}
                {{* counter = 0}}
                </div>
            {{/if}}
            {{* counter++ }}
        {{/props}}
    </script>

I'm creating my template via.

    var templateSource = $.templates(
        templateName,
        {
            markup: '#' + templateName,
            allowCode: true
        }   
    );

    for (var i = 0; i < dataSource.length; i++) {
        var template = templateSource.render(dataSource[i]);

Im also calling this on page load.

    $.views.settings.allowCode = true;

The statement of:

{{if counter == 0}}

And:

{{if counter == 4}}

Does not work as I would expect it to. Am I doing something wrong here?

My console logging shows that the comparison is true. Yet the log inside the condition bracket never gets hit. :(

My logging also shows that the counter is correctly incrementing.

Its probably something glaringly obvious but I cant see it :(.

1

There are 1 answers

1
BorisMoore On BEST ANSWER

You are modifying window.counter, but in your boolean test you are not looking at the value of window.counter. {{:counter}} and {{if counter}} are accessing the value of the counter property of the current data item - which is the object {key: ..., prop:...} since you are in the context of {{props ...}}.

Basically you can't access global vars from regular tags - only from {{*...}} and {{*:...}}

So you could do things like {{* if (window.counter==4) { }} ... {{* } }}.

See http://www.jsviews.com/#allowcodetag