Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 864
Josh Avatar asked Aug 29 '10 23:08

Josh


People also ask

How do I view an ERB file in HTML?

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.

Can you embed Ruby in HTML?

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.

Can you use JavaScript with Ruby on Rails?

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.


1 Answers

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.

like image 148
Yoni Baciu Avatar answered Sep 23 '22 01:09

Yoni Baciu