javascript - handlebars.js ...动态对象括号选择器
问题描述
我在特定项目上使用把手,我需要能够根据一些动态值选择选定的选项。
<select name="{{attribute_code}}">
{{#each values}}
<option value="{{value_index}}"
{{#ifCond ../../selectedProduct.[some_attribute] '==' value_index}}selected{{/ifCond}}>
{{label}}
</option>
{{/each}}
</select>
上面的块在一个each
有attribute_code
值的块内。在option
选择的循环中,我需要将的值映射attribute code
到some_attribute
。我已经浏览了文档和谷歌,我似乎无法找到解决方案。
所以例如让我们说attribute_code
有一个价值flavour
然后我需要选项中的表达式是......
{{#ifCond ../../selectedProduct.[flavour] '==' value_index}}selected{{/ifCond}}
想法?
解决方案
我通过制作自定义助手解决了这个问题......
Handlebars.registerHelper('ifDynamicPropertyCond', function (object, property, operator, value, options) {
switch (operator) {
case '==':
return (object[property] == value) ? options.fn(this) : options.inverse(this);
case '!=':
return (object[property] != value) ? options.fn(this) : options.inverse(this);
case '!==':
return (object[property] !== value) ? options.fn(this) : options.inverse(this);
case '===':
return (object[property] === value) ? options.fn(this) : options.inverse(this);
case '<':
return (object[property] < value) ? options.fn(this) : options.inverse(this);
case '<=':
return (object[property] <= value) ? options.fn(this) : options.inverse(this);
case '>':
return (object[property] > value) ? options.fn(this) : options.inverse(this);
case '>=':
return (object[property] >= value) ? options.fn(this) : options.inverse(this);
case '&&':
return (object[property] && value) ? options.fn(this) : options.inverse(this);
case '||':
return (object[property] || value) ? options.fn(this) : options.inverse(this);
default:
return options.inverse(this);
}
});
然后简单地...
{{#ifDynamicPropertyCond ../../selectedProduct ../attribute_code '==' value_index}}selected{{/ifDynamicPropertyCond}}
推荐阅读
- azure - 使用专用终结点时 Azure 弹性作业不起作用
- macos - macOS Catalina 升级后 Go 程序无法运行
- javascript - 如何使用 axios 将数据从 vuejs 表单提交到 zapier webhook?
- rxjs - RxJs 5 of.filter.mapTo 运算符 -> RxJs 6
- javascript - 针对另一个对象数组过滤对象数组?
- python - Excel 表格未对齐的列标题
- angular - 在 NgRx 中填充状态期间不满足状态不变性
- oracle - pl sql 也用查询声明变量
- java - 如何在java中编写自定义比较器?
- python - 使用 Scapy 删除重复的 IP 地址