Skip to content

Instantly share code, notes, and snippets.

@areichman
Created March 25, 2015 20:23
Show Gist options
  • Save areichman/2b2523aa3cf6ccb5c8c3 to your computer and use it in GitHub Desktop.
Save areichman/2b2523aa3cf6ccb5c8c3 to your computer and use it in GitHub Desktop.
Check box helper for Handlebars, based on the Rails check_box_helper
// Checkbox helper, based on http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box
//
// Usage:
// {{check_box object name="test" type="checkbox" value=true hidden="false"}}
//
// Note that the value in the hash can be specified with/without quotes so a proper type comparison
// can be made.
//
Handlebars.registerHelper('check_box', function(context, options) {
var checked = context !== undefined && context == options.hash.value ? 'checked' : '',
str = '<input ',
hidden = options.hash.hidden;
delete options.hash.hidden;
_.each(options.hash, function(val, key) {
str = str + key + '="' + val + '" ';
});
str = str + checked + '>';
// create a hidden form element to send unchecked values back to the server
if (hidden !== undefined) {
var hstr = '<input type="hidden" name="' + options.hash.name + '" value="' + hidden + '">';
str = hstr + str;
}
return new Handlebars.SafeString(str);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment