开发者

Comparing value of array in Mustache block loop

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 th开发者_开发百科ere 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 prefixes method to return an Array of Hashes:

def prefixes
  # figure out which one is selected by asking params...
  [ { :n => '03', :selected => false }, { :n => '04', :selected => true }, ... ]
end

and then something like this in your template:

<select id="phone_prefix" name="phone_prefix">
    {{#prefixes}}
        <option value="{{n}}" {{#selected}}selected="selected"{{/selected}}>{{n}}</option>
    {{/prefixes}}
</select>

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 params into your prefixes method.

Mustache is intentionally minimalistic and free of logic, it even says so on the homepage:

Logic-less templates.

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.


Rad! Thanks! That worked a treat. I ended up with the following method for prefixes and it works great:

def prefixes
  prefix_list = [{:n => "03", :selected => false}, {:n => "04", :selected => false}, {:n => "06", :selected => false}, {:n => "07", :selected => false}, {:n => "09", :selected => false}, {:n => "021", :selected => false}, {:n => "022", :selected => false}, {:n => "025", :selected => false}, {:n => "027", :selected => false}, {:n => "028", :selected => false}, {:n => "029", :selected => false}]
  prefix_list.each do |i|
    if i[:n] == "09"
      i[:selected] = true
    end
  end
  prefix_list
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜