Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

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

console.log(<%= @error %>)
like image 306
bill_cosby Avatar asked Nov 30 '25 04:11

bill_cosby


1 Answers

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.

like image 120
Sinan Guclu Avatar answered Dec 02 '25 18:12

Sinan Guclu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!