How to declare and update variables in google closure templates(soy template)

1.6k Views Asked by At

Lets take 2 arrays arr1 = ['a', 'b', 'c'] and arr2 = ['1' , '2', '3']. When passed these arrays as params to a soy template, I want to iterate as shown below and print an index that indicates total items iterated so far.

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}

Since variable declared using let cannot be re-assigned to a new value, is there a way in templates to achieve the logic I have shown above.

1

There are 1 best solutions below

0
On

Within the block, you can use three special functions that only take the iterator as their argument:

  • isFirst($var) returns true only on the first iteration.
  • isLast($var) returns true only on the last iteration.
  • index($var) returns the current index in the list. List indices are 0-based.

Then you can use index($j):

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

Hope I could help ;)

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