How to use Ruby code inside js.erb?

笑着哭i 提交于 2021-01-03 08:42:19

问题


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 %>)

回答1:


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.



来源:https://stackoverflow.com/questions/38392434/how-to-use-ruby-code-inside-js-erb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!