Rails Template Engine Iterate through Javascript Variable


How to use Rails template engine to iterate through Javascript variable(which has array) ? Most of the documents just mention about passing variable from controller to template engine, however I am interested in passing Javascript variable to template engine. How to do that? As mention in below in my index.html.erb file, the “event.data” is received from controller which I am passing to Javascript variable “my”. I want to iterate through this variable which holds the values and print them.

source.onmessage = (event) => {
var my = JSON.stringify(event.data)
<%= my.each do |val| %>
  <%= val %>
<% end %>



I don’t think that this is how that works….

JavaScript executes on the client in the browser, your ERB syntax is evaluated on the server.

Perhaps this mental model will help:

  1. Your browser makes an HTTP request to the server
  2. The server (Rails) executes some logic in the controller decides which view to render
  3. The server executes the ERB logic in your view file
  4. The server sends back a full HTML file (with JavaScript tags on it) to the browser
  5. The browser receives the page and paints/renders it. This includes executing any JacaScript tags it finds.

If you want to use some variable from JavaScript in your Rails code perhaps send it as a parameter with the HTTP request?

Thanks @jessevdp for your reply !

I am actually using Rails SSE using ActionController::Live and doing some calculations on controller and sending that data using sse.write method to my HTML. The HTML collects that data(object) as per below:

source.onmessage = (event) => {
     var result = JSON.stringify(event.data);

Now I need to collect this event.data and present in a HTML table. Is that doable using ERB template or need to use pure Javascript?

Ah sorry, it wasn’t to clear to me that you’re using some sort of live socket.

In this case… I think you need pure JavaScript. Although I’m not familiar with Rails SSE and what it can do for you.

You can always render the required HTML / ERB on the server and then send back the rendered HTML to be appended to the document via JavaScript.

Because rendering templates on the client using JavaScript gets annoying real fast.

That being said… you should really look into Turbo/Hotwire if you haven’t already.