JsRender:如何将变量传递给嵌套模板

doo*_*man 4 javascript jquery jsrender

我想在我的网页的不同部分使用嵌套模板.对于不同的部分,我需要从嵌套模板中的数组中获取值.我不能使用for循环,因为每个部分在网站上有不同的类和位置.是否可以将变量传递给嵌套模板?以下代码简化了我要实现的目标:

<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>
Run Code Online (Sandbox Code Playgroud)

另一个问题:当使用嵌套模板时,可以包含嵌套模板,如{{tmpl ="myBtnTmpl"/}},而不使用if语法?

谢谢!

Bor*_*ore 6

是的,您可以在您使用的标签上设置命名模板参数tmpl="myBtnTmpl"(无论是{{if}}标签还是{{for}}标签):

<div class="BigButton">
    {{for myData ~arrIndex=0 tmpl="myBtnTmpl"/}}
</div>
Run Code Online (Sandbox Code Playgroud)

然后,您可以像访问已注册的帮助程序一样访问模板参数 - 通过在名称后附加"〜".

<button class="btn">        
    {{:myData.myArray[~arrIndex].btnName}}
</button>
Run Code Online (Sandbox Code Playgroud)

顺便提一下,您还可以使用render方法传递变量和辅助函数(以及数据).我刚刚添加了一个新的示例演示.

所以,这是什么意思是,模板可以"参数"同样不管你是从代码渲染它们,或者声明在你上面的嵌套模板.