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.
View templates We will use HTML tags in Rails. HTML tags provide static web pages only but ERB tags give us dynamic information in that HTML template. To view the template file, go to Rails application >> app >> View>> Home folder where the templates files are available.
So far we've looked at using Ruby to create HTML output, but we can turn the problem inside out; we can actually embed Ruby in an HTML document. There are a number of packages that allow you to embed Ruby statements in some other sort of a document, especially in an HTML page.
Rails uses a technique called "Unobtrusive JavaScript" to handle attaching JavaScript to the DOM. This is generally considered to be a best-practice within the frontend community, but you may occasionally read tutorials that demonstrate other ways.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With