1

How do you loop through a ruby variable in a Haml javascript tag? I have a collection of @reviews that I need to loop through. How do you loop through this collection within a javascript tag?

  - content_for :javascript do

      = javascript_include_tag "jquery.expander"
        :javascript
        - @reviews.each do |review|
         $("#share#{review.id}").live('click', function() {
            FB.ui(
              {
                method: 'feed',
                name: '#{@product.name}',
                link: '#{@product.page_url(@locale)}',
                picture: '#{@product.image_url(@locale)}',
                caption: 'Dell Social Shop',
                description: '#{@product.description}'
              },
              function(response) {
                if (response && response.post_id) {
                  alert('Post was published.');
                } else {
                  alert('Post was not published.');
                }
              }
            );
          });}
Jason Wade
  • 87
  • 7
  • http://stackoverflow.com/questions/2962119/is-there-a-way-to-use-a-ruby-loop-inside-of-hamls-javascript-region – DanielG Sep 16 '11 at 19:39

2 Answers2

1

Try putting the - @reviews.each do |review| portion outside the = javascript_include_tag "jquey.expander" block, instead of inside it. Where it's sitting right now, it's probably being interpreted as javascript instead of Ruby, since it's indented under the :javascript line.

jefflunt
  • 33,527
  • 7
  • 88
  • 126
1

I found out that for Javascript code Erb templating works better than Haml templating. So i'd extract the loop body into an .erb partial, and do something like

= javascript_include_tag "jquery.expander"
= javascript_tag render(:partial => 'review.js.erb', :collection => @reviews)
Leonid Shevtsov
  • 14,024
  • 9
  • 51
  • 82