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

后端 未结 4 955

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: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 = <%= "
    #{@ruby_var.title}
    ".to_json %>; <% end %>

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

提交回复
热议问题