Josh
Josh

Reputation: 673

How to embed Ruby in JavaScript (Rails + .html.erb file)

I have a .html.erb file, with some javascript in it. I would like to do something like this:

var stuff = '<div><%= @ruby_var.title %></div>'

What is the best way to do this? I may be totally off... Thanks.

Upvotes: 22

Views: 37461

Answers (4)

robotdana
robotdana

Reputation: 532

<script>
 var stuff = '<div><%=escape_javascript @ruby_var.title %></div>'
</script>

in your .html.erb file will work fine.

Upvotes: 12

Yoni Baciu
Yoni Baciu

Reputation: 2707

To safely do this you need to use to_json:

<%= javascript_tag do %>
  var stuff = <%= @ruby_var.title.to_json %>;
<% end %>

This will ensure your code does not break if @ruby_var.title has a quote in it.

To include the divs I would do:

<%= javascript_tag do %>
  var stuff = <%= "<div>#{@ruby_var.title}</div>".to_json %>;
<% end %>

Note that there are no quotes around <%= %>, to_json takes care of that for you.

Upvotes: 27

Sandro L
Sandro L

Reputation: 1150

You can use the javascript_tag function to include Javascript in a .html.erb file.

Example:

javascript_tag "alert('This is a test')"

in your foo.html.erb will return

<script type="text/javascript">
//<![CDATA[
alert('This is a test')
//]]>
</script>

to the browser.

Upvotes: 3

AboutRuby
AboutRuby

Reputation: 8116

Ruby can't be run on the client, at least not with specialized browser plugins. Instead, look at using AJAX and RJS to query your Ruby web application from Javascript and insert any text it returns into your page.

Without more information, I don't think you're going to get any better answers. I might be totally off too, because I'm only guessing at what you really want to do.

Upvotes: 3

Related Questions