jquery - How to pass model attributes to coffeescript for select2 templating in Rails -
i'm trying implement select2 in rails 3.2 app.
specifically, want use templating display country select field country flags + country names.
i have country model , user model. country model has :code attribute. i'm using css sprite display flags, based on :code attribute.
<img class="flag flag-#{country.code}"> in user form have
<%= f.collection_select :country_id, country.order(:name), :id, :name, include_blank: true %> and in user.js.coffee.erb have
jquery -> format = (country) -> "<img class='flag flag-#{country.code}' src='#'/>" + country.name $('#prerep_country_id').select2 placeholder: "select country", allowclear: true, formatresult: format, formatselection: format i'm having trouble tying (probably part of ongoing learning of how asset pipeline , js.erb works).
currently select field rendered using select2, contains list of countries. no formatting.
how pass each country format = (country) function gets formatted flag?
thanks pointers.
from fine manual:
formatselection
function used render current selection.
formatselection(object)
and object parameter is
the selected result object returned
queryfunction.
and little further down see query about, in particular:
array of result objects. default renderers expect objects
id,textkeys.idattribute required, if custom renderers used.
and if @ example (http://jsfiddle.net/ambiguous/a73gc/), we'll see format function being passed country object id , text keys. you, on other hand, looking @ country.code there's nothing there , produce images this:
<img class='flag flag-' src='#'/> so don't flags.
try instead:
format = (country) -> "<img class='flag flag-#{country.id}' src='#'/>" + country.name #--------------------------------^^ presumably have height , width in img.flag css don't have worry how big flags are.
also, if you're using html5, can lose xml-style /> self-closing tag thing, <img ...> fine.
Comments
Post a Comment