如何在手柄模板中的单选按钮组中设置所选项目? [英] How to set the selected item in a radio button group in handlebars template?

查看:115
本文介绍了如何在手柄模板中的单选按钮组中设置所选项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在句柄模板中,如何仅使用模板将单选按钮组设置为正确的值?这可以直接在模板中完成吗?



例如,假设有一个单选按钮组如此:

 < label>< input type =radioname =modevalue =auto>自动< / label>< br> 
< label>< input type =radioname =modevalue =on> On< / label>< br>
< label>< input type =radioname =modevalue =off>关< / label>< br>

进入模板的数据具有模式值:

  {mode:on} 

我想在模板扩展后得到这个结果:

 < input type =radioname =modevalue = 自动 >自动<峰; br> 
< input type =radioname =modevalue =off>关闭< br>

以便表单中的HTML最初显示选中的开值。

解决方案

你可以编写一个帮助函数来帮助你处理这个用例。我喜欢将所有的块帮助器保存在指定的JS文件中,但可以将它们放在脚本中的任何位置。

  Handlebars。 registerHelper(setChecked,function(value,currentValue){
if(value == currentValue){
returnchecked;
} else {
return;
}
});

并且在您的模板中,您可以像这样使用它:

 < label>< input type =radioname =modevalue =auto{{{setChecked auto mode}}}> Auto<标签><峰; br> 
< label>< input type =radioname =modevalue =on{{{setChecked on mode}}}>开启< / label>< br>
< label>< input type =radioname =modevalue =off{{{setChecked off mode}}}>关< / label>< br>

这应该有效。

这个链接是阻止帮助者的好起点: http://handlebarsjs.com/block_helpers.html


In a handlebars template, how do you set a radio button group to the right value using only the template? Can this be done directly in the template?

For an example, let's say there's a radio button group like this:

<label><input type="radio" name="mode" value="auto">Auto</label><br>
<label><input type="radio" name="mode" value="on">On</label><br>
<label><input type="radio" name="mode" value="off">Off</label><br>

The data coming into the template has a value for mode:

{mode: "on"}

I want to end up with this after template expansion:

<input type="radio" name="mode" value="auto">Auto<br>
<input type="radio" name="mode" value="on" checked>On<br>
<input type="radio" name="mode" value="off">Off<br>

So that the HTML in the form initially shows the "on" value being selected.

解决方案

You can write a helper function to help you with this use case. I like to keep all my block helpers in a designated JS file - but you can put them anywhere inside your scripts.

Handlebars.registerHelper ("setChecked", function (value, currentValue) {
    if ( value == currentValue ) {
       return "checked";
    } else {
       return "";
    }
 });

and in your template you would use it like this:

<label><input type="radio" name="mode" value="auto" {{{setChecked auto mode}}}>Auto</label><br>
<label><input type="radio" name="mode" value="on" {{{setChecked on mode}}}>On</label><br>
<label><input type="radio" name="mode" value="off" {{{setChecked off mode}}}>Off</label><br>

This should work.

This link is a good starting point to block helpers: http://handlebarsjs.com/block_helpers.html

这篇关于如何在手柄模板中的单选按钮组中设置所选项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆