Forked from LukeChannings/handlebars-select-helper.js
Last active
March 23, 2016 23:57
-
-
Save bobjackman/fd8bd8681b4fd8965d42 to your computer and use it in GitHub Desktop.
A select helper for handlebars
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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/objectcurrentSelection
is optional. If omitted, or the not found amongoptionList
, the first option will be forcefully selected.