简体   繁体   English

handlebars.js…动态 object 支架选择器

[英]handlebars.js…dynamic object bracket selector

I am using handlebars on a particular project, and I need to be able to pick the selected option based on some dynamic values.我在特定项目上使用把手,我需要能够根据一些动态值选择选定的选项。

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

The above block is inside an each block which has an attribute_code value.上面的块在each块里面,它有一个attribute_code值。 In the option loop for the select, i need to map the value of attribute code to some_attribute .在 select 的option循环中,我需要将 map attribute code的值设置为some_attribute I have dug through the docs and google, and I can't seem to find a solution for this.我已经浏览了文档和谷歌,我似乎无法找到解决方案。

So for example let's say attribute_code has a value of flavour例如,假设attribute_code的值为flavour

Then I would need the expression in the option to be... {{#ifCond../../selectedProduct.[flavour] '==' value_index}}selected{{/ifCond}}然后我需要选项中的表达式是... {{#ifCond../../selectedProduct.[flavour] '==' value_index}}selected{{/ifCond}}

Thoughts?想法?

I solved this by making a custom helper...我通过制作自定义助手解决了这个问题......

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

and then simply...然后简单地...

{{#ifDynamicPropertyCond../../selectedProduct../attribute_code '==' value_index}}selected{{/ifDynamicPropertyCond}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM