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

前端 未结 4 1106
感动是毒
感动是毒 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:29

    I really liked the answer from ChrisV, once I understood it. I really struggled to get there from here. Please consider this a supporting comment to the answers above. I will say my use case was a tiny bit different. I'm using Express and I wanted to set the checkbox from a route. It wasn't totally clear to me how to call the helper function. Obviously, I'm using two different radio button groupings.

    In app.js, where I initially setup the view engine

    var hbs = require('hbs');
    hbs.registerPartials(__dirname + '/views/partials');
    hbs.registerHelper('checked', function (value, test) {
      if (value == undefined) return '';
      return value == test ? 'checked' : '';
    });
    app.set('view engine', 'hbs');
    

    I set the route in index.js

    var express = require('express');
    var router = express.Router();
    router.get('/display_form', function (req, res, next) {
    //... play with data.  use req.query.optionsRadiosA, etc...
    //  var outputA = "video"
        res.render('formpage', {
            title: 'Setup Page',
            optionsRadiosA: outputA,    // use variable
            optionsRadiosB: 'Audio'     // or use string
        });
    });
    

    and finally, my template, formpage.hbs (extract shown...)

    {{title}}

    Channel A Setup

    Channel B Setup

提交回复
热议问题