JsRender: how to pass variables to a nested template

I want to use a nested template in different parts of my web page. For different parts, I need to get the value from the array inside the nested template. I cannot use a for loop because each part has a different class and position on the website. Is it possible to pass a variable to a nested template? The following code simplifies what I am trying to achieve:

<script id="myBtnTmpl" type="text/x-jsrender"> <button class="btn"> {{:myData.myArray[INDEX_VARIABLE].btnName}} </button> </script> // Here I want to use INDEX_VARIABLE = 0 <div class="BigButton"> {{if myData tmpl="myBtnTmpl"/}} </div> // Here I want to use INDEX_VARIABLE = 1 <div class="MediumButton"> {{if myData tmpl="myBtnTmpl"/}} </div> // Here I want to use INDEX_VARIABLE = 2 <div class="SmallButton"> {{if myData tmpl="myBtnTmpl"/}} </div> 

Another question: when using nested templates, you can include nested templates like this {{tmpl = "myBtnTmpl" /}} without if syntax?

Thanks!

+4
source share
1 answer

Yes, you can set the parameters of the named template in the tag where you use tmpl="myBtnTmpl" (be it the {{if}} tag or the {{for}} tag):

 <div class="BigButton"> {{for myData ~arrIndex=0 tmpl="myBtnTmpl"/}} </div> 

You can then access the template parameter in the same way as a registered helper by adding '~' to the name.

 <button class="btn"> {{:myData.myArray[~arrIndex].btnName}} </button> 

By the way, you can also pass variables and helper functions (in addition to data) using the rendering method. I just added a new demo showing it.

So, this means that templates can be "parameterized" in the same way, regardless of whether you deny them from the code or declaratively, as in your nested templates above.

+6
source

All Articles