【问题标题】:How to declare and update variables in google closure templates(soy template)如何在谷歌闭包模板(大豆模板)中声明和更新变量
【发布时间】:2016-11-03 05:47:15
【问题描述】:

让我们采用 2 个数组 arr1 = ['a', 'b', 'c']arr2 = ['1' , '2', '3']强>。当将这些数组作为参数传递给大豆模板时,我想如下所示进行迭代并打印一个 index 表示到目前为止迭代的总项目。

index: 0 //variable assigned to 0 by default
{foreach $i in $arr1}
    {foreach $j in $arr2}
       index = index + 1; //variable incremented by 1
       {$index} th item //print item index
    {/foreach}
{/foreach}

由于使用 let 声明的变量不能重新分配给新值,模板中有没有办法实现我上面显示的逻辑。

【问题讨论】:

    标签: google-closure-templates soy-templates


    【解决方案1】:

    在块中,您可以使用三个仅以迭代器作为参数的特殊函数:

    • isFirst($var) 仅在第一次迭代时返回 true
    • isLast($var) 仅在最后一次迭代时返回 true
    • index($var) 返回列表中的当前索引。列表索引从 0 开始。

    那么你可以使用index($j):

    {foreach $i in $arr1}
      {foreach $j in $arr2}
        {index($j)}
      {/foreach}
    {/foreach}
    

    希望我能帮上忙;)

    来源:https://developers.google.com/closure/templates/docs/commands#foreach

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 2020-05-10
      相关资源
      最近更新 更多