How to set the selected item in a radio button group in handlebars template?

前端 未结 4 1089
感动是毒
感动是毒 2020-12-19 06:48

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,

4条回答
  •  醉梦人生
    2020-12-19 07:45

    Late addition for anyone else wanting the same: this works (quotes, undefined values, and all):

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

    Assuming a variable with the name of the input is passed to the Handlebars context, it is used as:

    Auto
    On
    Off

    Alternatively...

    If you don’t like having the helper calls in each input, you could wrap the inputs in a helper as follows:

    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;
    });
    

    Which would then be used as follows:

    {{#checked mode}}
    Auto
    On
    Off
    {{/checked}}

    Note a slightly different approach would be required for checkboxes, as they can have multiple values set.

    Remember helpers take precedence over context variables, so if you had an input named ‘checked’, you would have to use a path reference e.g. {{./checked}}.

提交回复
热议问题