Ruby methods in Javascript inside HAML

I have a jQuery script that adds a new field to a form, and this field contains dynamic information from an array. The problem is that I cannot figure out how to add array.each to populate the select field parameters in javascript without violating the HAML indentation and without causing errors.

Here is my best attempt that doesn't work:

%script(type="text/javascript") $('#mylink').click(function() { $('#mylink').after('<select> - myarray.each do |options| <option value="#{options.id}">#{options.name}</option> </select>); )}; 

Also tried this with a filter: javascript with no luck.

+53
javascript jquery ruby haml
Apr 14 '10 at 20:38
source share
2 answers

Usually, if something is a pain in haml, it means that you have to reorganize the complex bit to auxiliary or partial and call it.

 // some_helper.rb def new_snazzy_select_tag(options = []) select_tag 'tag_name_here', options.map { |option| [option.id, option.name] } end 

In addition, you should use the :javascript filter to render javascript, since it puts it in the script tag for you and allows indentation.

Finally, you can use #{ruby_expression} anywhere in haml, including filters :javascript , which is very convenient when you need to output the result of a ruby โ€‹โ€‹expression to places that are not the direct contents of the html elements.

 // some_view.html.haml :javascript $('#mylink').click(function() { $('#mylink').after("#{escape_javascript new_snazzy_select_tag(myarray)}"); }; 
+95
Apr 14 '10 at 21:19
source share

Try this, it should work (all I did was delete one space in the fifth line and add a final quote to the sixth):

 %script(type="text/javascript") $('#mylink').click(function() { $('#mylink').after('<select> - @myarray.each do |options| <option value="#{options.id}">#{options.name}</option> </select>'); )}; 

However, assuming you are running this with a ruby โ€‹โ€‹script or kind structure, why not just do it outside of the template? This is likely to be most appropriate. In rails / sinatra and other environments you can use a helper method to do this. If you look at the haml link, they actually hamper use - to evaluate ruby.

+8
Apr 14 '10 at 21:27
source share



All Articles