bill_cosby bill_cosby - 1 year ago 73
Ruby Question

How to use ruby code inside js.erb?

I'm able to render partial inside a modal using escape_javascript in js.erb file code:

For example:

$("body").append("<%= escape_javascript(render partial: 'example_partial') %>");

However, I can't seem to get results for:

console.log(<%= @error %>)

Nothing happens. Please help. TIA

Answer Source

ERB will output a plain string. JS needs inverted commas around a string for it to be recognized. You have missed them on your console.log() statement.

Change it to:

console.log('<%= @error %>');

You may also find the raw helper useful. This will call .to_s and .html_safe on any erb output:

console.log('<%= raw @error %>');

Read more about html_safe here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download