gpt4 book ai didi

javascript - Ractive 模板 if 语句不考虑父 if 语句

转载 作者:行者123 更新时间:2023-11-29 19:23:38 24 4
gpt4 key购买 nike

在我的模板中,我有一个字符串的 if 语句,它有时是未定义的,因为它在一个循环中,并且循环中的项目被删除并添加到其他事件发生时。

下面是一个示例模板,它是循环内的部分模板。当将 myString 从 JS 中的值更改为未定义时,此部分会导致 RactiveJS 中发生未定义错误。

{{#if myString}}
{{#if myString.indexOf('hello people') > -1}}
<p>Hello all the people</p>
{{/if}}
Why are the people?
{{/if}}

要阻止错误,我必须执行以下操作:

{{#if myString}}
{{#if myString && myString.indexOf('hello people') > -1}}
<p>Hello all the people</p>
{{/if}}
Why are the people?
{{/if}}

这个在子 if 语句中带有 && 的模板对我来说意义不大,因为它应该考虑父 if 语句并且不会导致错误。

Ractive 翻译 if 语句的方式有问题吗?或者这对于模板语言来说是正常的吗?

最佳答案

Ractive 的当前版本“扁平化”了依赖于您的数据的图表;这样做的一个副作用是表达式有时会在它们被删除之前立即更新,这会导致像这样的不良情况。这可能会在下一个版本 (0.8) 中发生变化。目前,最好的解决方法可能是您已经在使用的解决方法,但如果这样可以使模板更具可读性,您也可以将其封装为一个函数:

{{#if isHelloPeople(myString) }}
<p>Hello all the people</p>
{{/if}}
var ractive = new Ractive({
data: {
myString: 'hello people',
isHelloPeople: function ( str ) {
return str && ~str.indexOf( 'hello people' );
}
},
// ...
});

关于javascript - Ractive 模板 if 语句不考虑父 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31917743/

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