JsRender: How to pass variables into a nested template

半城伤御伤魂 提交于 2019-12-12 12:02:51

问题


I want to use a nested template in different parts of my webpage. For the different parts I need to get a value from an array within the nested template. I cannot use a for loop because each part has different class and position on the website. Is it possible to pass a variable into the 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 is it possible to include nested templates like this {{tmpl="myBtnTmpl"/}} without the if syntax?

Thanks!


回答1:


Yes, you can set named template parameters on the tag where you are using tmpl="myBtnTmpl" (whether that be an {{if}} tag or a {{for}} tag):

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

Then you can access the template parameter in the same way you would access a registered helper - by appending '~' to the name.

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

Incidentally, you can also pass variables and helper functions (in addition to the data) with the render method. I just added a new sample demo showing that.

So what this means is that templates can be 'parameterized' similarly whether you are rendering them from code, or declaratively as in your nested templates above.



来源:https://stackoverflow.com/questions/11325085/jsrender-how-to-pass-variables-into-a-nested-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!