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 somet开发者_开发技巧hing like this:
var stuff = '<div><%= @ruby_var.title %></div>'
What is the best way to do this? I may be totally off... Thanks.
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.
<script>
var stuff = '<div><%=escape_javascript @ruby_var.title %></div>'
</script>
in your .html.erb file will work fine.
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.
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.
精彩评论