0

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!

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 %>');

1 Comment

I'm okay with this as long as any minifiers are aware that this js is not cacheable. The js would need to be generated every page load, and is an extra request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.