Nekkoru
Nekkoru

Reputation: 1165

Using erb tags in jquery?

I'm using Sinatra and Datamapper. In one part of my app, I want to dynamically add new <select> elements to a table which acts as a form. The <select> element contains all of the elements from my Personnel class. If I were to do this in regular ERB, I'd do:

<select>
<% @personnel.each do |p| %>
  <option> <%= p.name %> </option>
<% end %>
</select>

However, in JQuery this doesn't work. I was wondering if there was anything I could do to dynamically add <select> elements like the one above.

Upvotes: 0

Views: 161

Answers (2)

Patrick Oscity
Patrick Oscity

Reputation: 54684

You can also keep the JS file separate from the html by writing a route like this:

get '/myscript.js' do
  content_type :js
  erb :myscript
end

Of course this can be generalized but i'll leave that up to you ;-)

Upvotes: 1

Nekkoru
Nekkoru

Reputation: 1165

Apparently the solution was incredibly simple. Instead of putting my Jquery script into the public directory, as you normally would, the script should be written as part of the .erb template. Then Sinatra takes care of generating proper HTML tags for insertion. You can then use the <% %> elements inside of <script> </script> - works perfectly.

Upvotes: 1

Related Questions