Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I took the <code>{{#each}}</code> helper as inspiration, and wrote a custom helper that does the same thing: loops over a list, and continually appends the contents of the arguments to an output string. (From here: <a href="http://handlebarsjs.com/block_helpers.html" rel="nofollow noreferrer">Handlebars block helpers</a>)</p> <p>In this case, I'm not passing in a chunk of template HTML to serve as the function's <code>options</code> parameter, like you would when using <code>{{#each}}</code>. Instead I am just building up the <code>&lt;option&gt;</code> tags by brute force, and testing every iteration of the <code>context</code> list. Lastly, I return a big long string of <code>&lt;option&gt;&lt;/option&gt;</code> tags, and hopefully one of them has <code>selected="selected"</code>.</p> <p>The function:</p> <pre><code>Handlebars.registerHelper('options_selected', function(context, test) { var ret = ''; for (var i = 0, len = context.length; i &lt; len; i++) { var option = '&lt;option value="' + context[i]+'"'; if (test.toLowerCase() == context[i].toLowerCase()) { option += ' selected="selected"'; } option += '&gt;'+ Handlebars.Utils.escapeExpression(context[i]) + '&lt;/option&gt;'; ret += option; } return new Handlebars.SafeString(ret); }); </code></pre> <p>The tag in use:</p> <pre><code>&lt;script id="form-state" type="text/x-handlebars-template"&gt; &lt;select name="state"&gt; {{{options_selected states selectedState}}} &lt;/select&gt; &lt;/script&gt; </code></pre> <p>Please suggest any edits that would improve this, thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload