google-closuregoogle-closure-templates

Cannot modify a value in a Soy template


{let $first: 10 /} // this is a single line soy comment
  {if $first > 5 }
  {$first}<br/>
  {let $first:$first-1 /}
  {/if}
{$first}

I tried this, and it prints: 10 10

Ideally, it should print: 10 9 ..

Can you please identify what's wrong in my code?


Solution

  • First of all, you cannot really overwrite the value of $first. The documentation states local variables defined by let are not modifiable. This is because whenever you alias a value with let, a new variable is created in the compiled output. Moreover, the scoping rules of soy expressions aren't the same as in Javascript (but you could think of {let} having similar semantics to ECMAScript 6's let statement, that is, non-hoisted, block-scoped).

    In your code:

    {let $first: 10 /}           /* 1 */
    {if $first > 5}
      {$first}<br/>
      {let $first¹: $first-1 /}  /* 2 */
                                 /* 3 */
    {/if}
    {$first}                     /* 4 */
    

    what's happening is: