JavaScript

Handlebars - Calling a helper function from another helper

By Niall Kader1 min read

Here's  a helper that will create the options for a selectbox, you just pass in the selected value and the options. If the option values are different than the options text, then pass in a third param that has the text for each option.

Handlebars.registerHelper('selectBoxOptions', function(selectedValue, optionValues, optionTextStrings){

  var html = "";
  var value = null;
  var text = null;
  var selelctedAttr = "";

  for(var x=0; x < optionValues.length; x++){

    value = optionValues[x];

    if(optionTextStrings && optionTextStrings[x]){

      text = optionTextStrings[x]

    }else{

      text = value;

    }

    if(value == selectedValue){

      selectedAttr = ' selected="selected" ';

    }else{

      selectedAttr = "";

    }

    html += '<option value="' + value +'"' + selectedAttr + '">' + text + "</option>";

  }

  return new Handlebars.SafeString(html);
});

Here's an example of how you might call this helper from another helper:

Handlebars.registerHelper('operatorOptions', function(dataType, selectedValue){

  var options = [];

  switch(dataType){
    case "text":
      options = ["contains", "does not contain", "is", "is not", "begins with","ends with"];
    break;
    case "number":
      options = ["is", "is not", "greater than", "less than", "in range"];
    break;
    case "date":
      options = ["is", "is not", "is before","is after", "in range"];
    break;
    case "boolean":
      options = ["is", "is not"];
    break;
    default:
      throw new Error("invalid data type");
  }

  return Handlebars.helpers.selectBoxOptions(selectedValue, options);

});