timiambaye
timiambaye

Reputation: 9

Handlebars confusion I don't get it

I have tried my best to debug thoroughly but i just can't figure out why this code does not work.. I know its my fault but i can't find the bug. Please help me guys

https://codepen.io/blaze4dem/pen/zZmqKa

    var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);

Handlebars.registerHelper("makeradio", function(name, options){
      var radioList = options.fn();
      radioList = radioList.trim().split("\n");

      var output = "";
      for(var val in radioList){
        var item = radioList(val).trim();
      output += '<input type="radio" name="'+ name +'" value="'+ item +'"> '+ item + '<br/>';
      };
      return output;
    });

    var tempdata = template({});
    document.getElementById('dynamic').innaHTML += tempdata;

Upvotes: 1

Views: 58

Answers (1)

Sushanth --
Sushanth --

Reputation: 55750

I see 3 issues in the code.

  • for in is best to iterate over objects. In this case when you split the output is an array. User for loop instead.
  • You have a typo, when you are replacing the element. Supposed to be innerHTML
  • radioList(val) --> () will invoke a method, where as you want to access a property. So it has to be [].

You can try this approach. But I strongly feel that you should be using a different delimiter instead of \n

var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);

Handlebars.registerHelper("makeradio", function(name, options) {
  debugger;
  var radioList = options.fn();
  var hasSpaces = radioList.indexOf(' ') > -1;
  var hasNewLines = radioList.indexOf('\n') > -1;

  if (hasNewLines) {
    radioList = radioList.trim().split("\n");
  } else if (hasSpaces) {
    radioList = radioList.trim().split(" ");
  }

  var output = "";
  // for in is best to iterate over objects.
  // use for loop instead
  for (var i = 0; i < radioList.length; i++) {
    var item = radioList[i].trim();
    output += '<input type="radio" name="' + name + '" value="' + item + '"> ' + item + '<br/>';
  };
  return output;
});

var tempdata = template({});
document.getElementById('dynamic').innerHTML += tempdata;

Check Fiddle

Upvotes: 1

Related Questions