我需要有关车把帮手的帮助:
从数据库中选择的数据:
{ _id: 5b598e31f24e7f820d2d422d, key: 'c-1', name: 'C#' },
{ _id: 5b598e61f24e7f820d2d4234, key: 'node-js', name: 'Node.js'}
HBS生成动态选择选项:
{{#each tags}}
<option value="{{_id}}">{{name}}</option>
{{/each}}
HTML:
<select multiple="" class="custom-select" name="skills">
<option value="5b598e22f24e7f820d2d422b">Javascript</option>
<option value="5b598e29f24e7f820d2d422c">C++</option>
<option value="5b598e31f24e7f820d2d422d">C#</option>
<option value="5b598e61f24e7f820d2d4234">Node.js</option>
</select>
如何将selected="selected"
添加到具有相同ID的选项中?有什么优雅的解决方案吗?
对于信号选择字段,我使用代码:
{{#select post.position.id}}
{{#each categories}}
<option value="{{id}}">{{name}}</option>
{{/each}}
{{/select}}
helpers.js
_helpers.select = function(selected, options){
return options.fn(this).replace(new RegExp(' value=\"'+ selected + '\"'), '$&selected="selected"');
}
答案 0 :(得分:1)
您可以使用像这样的助手来测试您的字符串是否相同:
Handlebars.registerHelper('test', function(lvalue, operator, rvalue, options) {
var doDisplay = false;
var items = (""+rvalue).split("|");
var arrayLength = items.length;
for (var i = 0; (i < arrayLength); i++) {
if (operator == "eq") {
if (lvalue == items[i]) {
doDisplay = true;
}
} else if (operator == "ne") {
if (lvalue != items[i]) {
doDisplay = true;
}
} else if (operator == "gt") {
if (parseFloat(lvalue) > parseFloat(items[i])) {
doDisplay = true;
}
} else if (operator == "lt") {
if (parseFloat(lvalue) < parseFloat(items[i])) {
doDisplay = true;
}
}else if (operator == "le") {
if (parseFloat(lvalue) <= parseFloat(items[i])) {
doDisplay = true;
}
}else if (operator == "ge") {
if (parseFloat(lvalue) >= parseFloat(items[i])) {
doDisplay = true;
}
}
}
if (doDisplay) {
return options.fn(this);
} else {
return "";
}
});
然后像这样在HTML代码中使用帮助程序:
<select multiple="" class="custom-select" name="skills">
<option value="5b598e22f24e7f820d2d422b" {{#test name 'eq' 'Javascript'}}selected{{/test}}>Javascript</option>
<option value="5b598e29f24e7f820d2d422c" {{#test name 'eq' 'C++'}}selected{{/test}}>C++</option>
<option value="5b598e31f24e7f820d2d422d" {{#test name 'eq' 'C#'}}selected{{/test}}>C#</option>
<option value="5b598e61f24e7f820d2d4234" {{#test name 'eq' 'Node.js'}}selected{{/test}}>Node.js</option>
</select>