Search code examples
javascriptjsviews

How to define a variable an use it on the jsviews templates?


I would like to define a unique id, for a html element, that I will have to pass as a parameter of a helper function.

The unique Id is generated correctly with the another helper function (genearteUniqueId) but I can't get it stored in a variable to reuse it and pass it to another function. Does anybody have run into this challenge when using Jsviews?

I tried assigning the generateUniqueId() result to a defined variable as in {{:uniqueId=~generateUniqueId()}} and then pass the uniqueId variable as a parameter {{:~decorator(uniqueId}} but it didn't work.

<div class="graph-row">
   <span class="bar-graph" id="{{:~generateUniqueId()}}" {{:~decorator(outOfPockets[0].paid, outOfPockets[0].total, ~generateUniqueId())}}></span>
</div>

Solution

  • Well you can define your own getUniqueId() which gets the last generated id, along the lines of

    var cnt = 0, lastId;
    
    var myTmpl = $.templates("#myTmpl"),
      data = {},
      helpers = {
        generateUniqueId: function() {return (lastId = cnt++);},
        getUniqueId: function() {return lastId;},
        decorator: function(id) {return "title=YES" + id;}
      };
    
    myTmpl.link("#page", data, helpers);
    

    and write

    <span id="{{:~generateUniqueId()}}" {{:~decorator(~getUniqueId())}}></span>
    

    Alternatively, (though this is better avoided if you are using JsViews data-linking, rather than just JsRender rendering), you can set allowCode to true, with the following approach:

    $.views.settings.allowCode(true);
    var cnt = 0;
    function genId() {return cnt++;}
    function dec(id) {return "title=YES" + id }
    

    and write:

    <span id="{{*:(theid=genId())}}" {{*:dec(theid)}}>c</span>