本文介绍了如何在Handlebars模板中设置选定的选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用像这样的Handlebars.js模板......
With a Handlebars.js template like this...
<select>
<option value="Completed">Completed</option>
<option value="OverDue">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
</select>
...和这样的数据......
... and data like this...
{
"id" : 1,
"name" : "World"
"status" : "OverDue",
"date" : "2012-12-21"
}
我想要渲染像这样的HTML。
I want to render HTML like this.
<select>
<option value="Completed">Completed</option>
<option value="OverDue" selected="selected">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
</select>
哪种方式最简单?
推荐答案
我找到了很多过于复杂的解决方案,并决定使用Handlebars助手编写自己的解决方案。
I found a lot of over complicated solutions and decided to write my own using a Handlebars helper.
使用此部分(使用Jquery) )...
With this partial (using Jquery) ...
window.Handlebars.registerHelper('select', function( value, options ){
var $el = $('<select />').html( options.fn(this) );
$el.find('[value="' + value + '"]').attr({'selected':'selected'});
return $el.html();
});
您可以使用{{#select status}}来包装Handlebars模板中的选项...
You can wrap selects in your Handlebars template with {{#select status}}...
<select>
{{#select status}}
<option value="Completed">Completed</option>
<option value="OverDue">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
{{/select}}
</select>
并以此结束......
and end up with this...
<select>
<option value="Completed">Completed</option>
<option value="OverDue" selected="selected">OverDue</option>
<option value="SentToPayer">SentToPayer</option>
<option value="None">None</option>
</select>
Presto!
这篇关于如何在Handlebars模板中设置选定的选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!