首页 > 解决方案 > handlebars.js ...动态对象括号选择器

问题描述

我在特定项目上使用把手,我需要能够根据一些动态值选择选定的选项。

<select name="{{attribute_code}}">
    {{#each values}}
        <option value="{{value_index}}"
            {{#ifCond ../../selectedProduct.[some_attribute] '==' value_index}}selected{{/ifCond}}>
            {{label}}
        </option>
    {{/each}}
</select>

上面的块在一个eachattribute_code值的块内。在option选择的循环中,我需要将的值映射attribute codesome_attribute。我已经浏览了文档和谷歌,我似乎无法找到解决方案。

所以例如让我们说attribute_code有一个价值flavour

然后我需要选项中的表达式是...... {{#ifCond ../../selectedProduct.[flavour] '==' value_index}}selected{{/ifCond}}

想法?

标签: javascripthandlebars.js

解决方案


我通过制作自定义助手解决了这个问题......

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}}


推荐阅读