如何在手柄模板中的单选按钮组中设置所选项目?

jfr*_*d00 5 javascript template-engine mustache handlebars.js

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

举个例子,假设有一个这样的单选按钮组:

<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>
Run Code Online (Sandbox Code Playgroud)

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

{mode: "on"}
Run Code Online (Sandbox Code Playgroud)

我想在模板扩展后最终得到这个:

<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>
Run Code Online (Sandbox Code Playgroud)

因此表单中的HTML最初显示选中的"on"值.

小智 11

您可以编写辅助函数来帮助您使用此用例.我喜欢将所有块助手保存在指定的JS文件中 - 但是您可以将它们放在脚本中的任何位置.

Handlebars.registerHelper ("setChecked", function (value, currentValue) {
    if ( value == currentValue ) {
       return "checked";
    } else {
       return "";
    }
 });
Run Code Online (Sandbox Code Playgroud)

在你的模板中,你会像这样使用它:

<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>
Run Code Online (Sandbox Code Playgroud)

这应该工作.

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


Chr*_*isV 6

对于想要相同的其他人的后期添加:这有效(引号,未定义的值等):

Handlebars.registerHelper('checked', function(value, test) {
    if (value == undefined) return '';
    return value==test ? 'checked' : '';
});
Run Code Online (Sandbox Code Playgroud)

假设一个带有输入名称的变量被传递到 Handlebars 上下文,它被用作:

<input type="radio" name="mode" value="auto" {{checked mode 'auto'}}>Auto<br>
<input type="radio" name="mode" value="on" {{checked mode 'on'}}>On<br>
<input type="radio" name="mode" value="off" {{checked mode 'off'}}>Off<br>
Run Code Online (Sandbox Code Playgroud)

或者...

如果您不喜欢在每个输入中都调用 helper,您可以将输入包装在一个 helper 中,如下所示:

Handlebars.registerHelper('checked', function(value, options) {
    const div = document.createElement('div'); // create a container div
    div.innerHTML = options.fn(this);          // parse content into dom
    div.querySelectorAll('input[type=radio]').forEach(function(input) {
        // if input has value matching supplied value, check it
        if (input.value == value) input.defaultChecked = true;
    });
    return div.innerHTML;
});
Run Code Online (Sandbox Code Playgroud)

然后将按如下方式使用:

{{#checked mode}}
<input type="radio" name="mode" value="auto">Auto<br>
<input type="radio" name="mode" value="on">On<br>
<input type="radio" name="mode" value="off">Off<br>
{{/checked}}
Run Code Online (Sandbox Code Playgroud)

请注意,复选框需要一种稍微不同的方法,因为它们可以设置多个值。

请记住,助手优先于上下文变量,因此如果您有一个名为“已检查”的输入,则必须使用路径引用,例如{{./checked}}.