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

后端 未结 4 954

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

var stuff = \'
<%= @ruby_var.title %>
\'
相关标签:
4条回答
  • 2021-02-05 07:33
    <script>
     var stuff = '<div><%=escape_javascript @ruby_var.title %></div>'
    </script>
    

    in your .html.erb file will work fine.

    0 讨论(0)
  • 2021-02-05 07:34

    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.

    0 讨论(0)
  • 2021-02-05 07:39

    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.

    0 讨论(0)
  • 2021-02-05 07:42

    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.

    0 讨论(0)
提交回复
热议问题