So I am trying to render a select drop-down from an array using Mustache and Sinatra. The template code currently looks like this:
<select id="phone_prefix" name="phone_prefix">
{{#prefixes}}
<option value="{{to_s}}" {{selected}}>{{to_s}}</option>
{{/prefixes}}
</select>
With the following method in the view it is rendering each item of the array:
def prefixes
["03", "04", "06", "07", "09", "021", "022", "025", "027", "028", "029"]
end
For the {{selected}} value in the mustache template I need to do a comparison on the array item currently being iterated over and a query string value coming in via params[:phone_prefix] which for instance is "09". Then when there is a match return a value of "selected" to a selected method to pass to mustache.
Any help would be greatly appreciated.
Push the logic into your Ruby and just feed data to Mustache. Update your
prefixesmethod to return an Array of Hashes:and then something like this in your template:
I’ve only used Mustache in JavaScript so I might be missing something in the Ruby flavor but something close to that should work, you just have to get information from
paramsinto yourprefixesmethod.Mustache is intentionally minimalistic and free of logic, it even says so on the homepage:
So all your logic goes in your code and you just set a bunch of variables and flags for Mustache to do things with. The only logic available in the template is “is this thing true?” and “can I iterate over this thing?”; anything more complicated than that has to go in the code that is preparing data for Mustache.