Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bobjackman/fd8bd8681b4fd8965d42 to your computer and use it in GitHub Desktop.
Save bobjackman/fd8bd8681b4fd8965d42 to your computer and use it in GitHub Desktop.
A select helper for handlebars
Handlebars.registerHelper( 'select-options', function( items, selectedValue, options ) {
// ======== Ensure `items` is Object/Hash
if( items instanceof Array ) {
var temp = {};
for( var i in items ) {
var value = items[i];
temp[value] = value;
}
items = temp;
}
// ======== Generate HTML
var selectedFound = !!items[selectedValue];
var html = '';
var first = true;
for( var value in items ) {
var display = items[value];
var selected = ((!selectedFound && first) || (selectedFound && (value == selectedValue)));
html += '<option value="' + value + '"' + (selected ? ' selected="selected"' : '') + '>' + display + '</option>';
first = false;
}
return new Handlebars.SafeString( html );
});
@bobjackman
Copy link
Author

The original broke when I tried to use a nested {{#each}} to generate the <option /> tags, so I forked it to the above.

Usage

optionList can be an array or a hash/object
currentSelection is optional. If omitted, or the not found among optionList, the first option will be forcefully selected.

<select id="my-select" class="foo" name="flappity">
    {{select-options optionList currentSelection}}
</select>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment