如何在aurelia中重复将字符串转换为表达式值?

问题描述

重复用于循环的数组

let loopArr = ["item.name + ' /'+ item.displayName? item.displayName: item.otherdisplayName","item.description + ' /'+ item.anotherDescription"]

模板

<div repeat.for = item of data">
    <div repeat.for = "row of loopArr">
        <span textcontent.bind="renderRow(row,item)></span>
    </div>
</div>

组成方法

renderRow(row,item){
    return eval(row)
}

实际上我想在模板中像下面这样显示

<div repeat.for = item of data">
    <div repeat.for = "row of loopArr">
        <span>${item.name + ' /'+ item.displayName? item.displayName: item.otherdisplayName} </span>
        <span>${item.description + ' /'+ item.anotherDescription} </span>
    </div>
</div>

由于我想循环遍历 dynamic loopArr ,而不是使用eval从字符串转换为值,是否有更好的方法来从字符串计算值?另外,eval不适用于多行语句,是否有其他方法/方式来解决上述问题?

如何将字符串转换为值并显示在aurelia模板中?

任何帮助将不胜感激!

解决方法

我不确定为什么要添加字符串格式的逻辑并使用{​​{1}}。您可以将其直接添加到eval并显示:

template

让我们假设您有一个自定义字符串格式列表,并且正在从另一个文件导入它们。您可以创建函数数组,而不是字符串数组。与运行<div repeat.for="item of data"> <span>${item.name + '/' + (item.DisplayName ? item.DisplayName: item.otherDisplayName)}</span> <span>${item.description + ' / '+ item.anotherDescription} </span> </div>

相比,这是延迟字符串创建的更好的方法
eval

,然后在displayTemplates = [ item => item.name + '/' + (item.DisplayName ? item.DisplayName: item.otherDisplayName),item => item.description + '/'+ item.anotherDescription ] 中:

template

此外,您的字符串格式中存在逻辑错误。与三元运算符相比,<div repeat.for="item of data"> <template repeat.for="func of displayTemplates"> <span>${ func(item) }</span> <!-- call each func on item object --> </template> </div> 运算符具有higher precedence

所以

+

实际评估为

item.name + '/' + item.DisplayName ? item.DisplayName : item.otherDisplayName

因此,该表达式将始终求值为(item.name + '/' + item.DisplayName) ? item.DisplayName : item.otherDisplayName ,因为item.DisplayName永远不会是falsy

您需要在三元操作周围添加item.name + '/' + item.DisplayName

()