gpt4 book ai didi

raku - WebApp::Template 条件行为和变量的使用

转载 作者:行者123 更新时间:2023-12-04 12:02:41 25 4
gpt4 key购买 nike

使用提供的模板语言,我总是可以访问 $_ 或 Hash 引用以进行迭代,这很好。

# In routes
get -> 'somestuff' {
my $stuff = %{ arr => [ {stuff => 'stuff1' , nbr => 1 }, {stuff => 'stuff2', nbr => 2 } ] };
template 'somestuff.crotpl', $stuff;
}
# In somestuff.crotpl
<?$_.elems>
<$_> <br>
<@arr> <.stuff> = <.nbr> <br> </@>
</?>

但是测试不存在的键/值 <?{.not-here}> ...</?>抛出异常,这是正常行为吗?

我似乎没有在文档中说明的变量仅在从与路由上下文无关的模板子例程中调用它们时才可用(如测试文件所示: https://github.com/croservices/cro-webapp/blob/master/t/test-data/cond-var.crotmp)。对不存在的变量进行测试也会引发异常。

最佳答案

<.foo> 的文档取消引用如下:

If the current topic does the Associative role, then this form will prefer to take the value under the name hash key, falling back to looking for a method name if there is no such key.



因此,如果没有这样的键,那么它确实会退回到方法调用,并且(在 Raku 中通常是这种情况)如果没有这样的方法是错误的。所以是的,这是预期的行为。

还有一些明确的形式总是会进行哈希访问(软故障)或方法分派(dispatch)(如果没有这种方法,则会出错。再次引用文档的相关位:

  • <.elems()> will always be a method call, even if used on an Associative (so can be used to overcome the key fallback)
  • <.<elems>> will always be a hash index


这些在模板语言中一致地应用,所以 <$var<foo>><?{ $var<foo> }>可以使用(授予文档可能会更清楚地说明这一点)。

模板顶层范围内的唯一变量是 $_ , 初始化为调用 template 时传递的值.迭代、子例程和宏都可能引入变量。如文档中所述:

It is a template compilation time error to refer to a variable that does not exist.



这意味着它们遵循与 Raku 中的词汇变量相同的规则。该错误是在模板编译时产生的,这意味着可以编写一个编译所有模板的单元测试,以确保至少不存在这种错误。

一般来说,模板语言遵循 Raku 语义,唯一的显着差异是 <.foo>作用于 Associative更像 .<foo>:exists ?? .<foo> !! .foo .

关于raku - WebApp::Template 条件行为和变量的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58939333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com