[英]handlebars.js…dynamic object bracket selector
我在特定項目上使用把手,我需要能夠根據一些動態值選擇選定的選項。
<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
值。 在 select 的option
循環中,我需要將 map 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}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.