简体   繁体   English

无法修改Soy模板中的值

[英]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 我试过了,它打印:10 10

Ideally, it should print: 10 9 .. 理想情况下,它应该打印:10 9 ..

Can you please identify what's wrong in my code? 您能确定我的代码有什么问题吗?

First of all, you cannot really overwrite the value of $first . 首先,您不能真正覆盖$first的值。 The documentation states local variables defined by let are not modifiable. 文档指出let定义的局部变量不可修改。 This is because whenever you alias a value with let , a new variable is created in the compiled output. 这是因为每当您使用let别名一个值时,都会在编译输出中创建一个新变量。 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). 此外,大豆表达式的作用域规则与Javascript中的规则不同(但您可以想到{let}语义与ECMAScript 6的let语句相似,即非悬挂式,块作用域化)。

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: 发生了什么事:

  • In (1), $first is an alias for the value 10 . 在(1)中, $first是值10的别名。 A variable is introduced to hold this value. 引入一个变量来保存该值。

  • In (2): 在(2)中:

    Right hand: $first takes its value from (1), because it is defined in a parent block. 右手: $first从(1)中获取其值,因为它是在父块中定义的。

    Left hand: $first¹ is being aliased to the value resulting from $first - 1 = 10 - 1 = 9. Because the definition of $first can't be overwritten, a new variable is introduced, different from (1). 左手: $first¹被别名为$first -1 = $first¹ = 9的值。由于$first的定义不能被覆盖,因此引入了一个新变量,与(1)不同。 There are two things to note: 有两件事要注意:

    a. 一种。 The value for $first¹ is 9, but it's never read in this snippet. $first¹值为9,但是在此代码段中从未读取。

    b. b。 $first¹ only "lives" within the block it was defined, that is, inside {if...} . $first¹仅“存在”于已定义的块内,即{if...}内部。 In fact, if you were to insert {$first} in (3), it would output 9. 实际上,如果要在(3)中插入{$first} ,它将输出9。

  • In (4), the value of $first¹ , being out of the scope introduced by the {if} block, can no longer be read, so $first from (1) is the only one visible, yielding 10. It makes use of the same variable as (1) in the compiled output. 在(4)中,无法再读取{if}块引入的范围之外的$first¹的值,因此(1)中的$first是唯一可见的值,产生10。它利用了与编译输出中的(1)相同的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM