Pavel
Pavel

Reputation: 1974

Rails: ruby code in javascript

I have a problem with a passing ruby code in javascript script tag

Now I have this code:

<script>
  var offer_foto = {
    slide_offer_preview_1: ['one.jpg', 'two.jpg', 'three.jpg'],
    slide_offer_preview_2: ['four.jpg', 'five.jpg', 'six.jpg']
  }
</script>

My Ruby code

<% for i in 0..@page[:proposals].count - 1 %>
  <%= @page[:proposals][i][:hotels][0]['hotel_images'].map{|f| f['url']} %>
<% end %>

In Javascript I need

slide_offer_preview_i: <%= @page[:proposals][i][:hotels][0]['hotel_images'].map{|f| f['url']} %>

Unfortunately I don't know how ti get it because I know Javascript not quite well. If you need more information please comment. Thanks!

Upvotes: 0

Views: 93

Answers (2)

000
000

Reputation: 27227

You should do this in the controller, not in the template. Keep logic far away from your templates.

In your controller:

@slide_offer_previews = []
for i in 0..@page[:proposals].count - 1
  @slide_offer_previews << @page[:proposals][i][:hotels][0]['hotel_images'].map{|f| f['url']}
end

Then in your view:

slide_offer_preview_i: <%= @slide_offer_previews[i] %>

Alternatively, if @page[:proposals][i] is an object, then add a method to your class:

def hotel_image_urls
  self[:hotels][0]['hotel_images'].map{|f| f['url']}
end

then in your view:

slide_offer_preview_i: <%= @page[:proposals][i].hotel_image_urls() %>

edit: Sorry, this doesn't even make syntactical sense. Disregard this alternate.

Upvotes: 1

NM Pennypacker
NM Pennypacker

Reputation: 6942

I'm with Joe Frembach, you should do this in the controller. However, if you do need to embed Ruby into Javascript, you can do so by adding .erb (file_name.js.erb) to the file extension, in which case you can do something like:

alert('<%= @your_embedded_variable %>');

Upvotes: 0

Related Questions