简体   繁体   English

如何在js.erb中使用Ruby代码?

[英]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: 我可以在js.erb文件代码中使用escape_javascript来渲染模态内部的部分内容:

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

However, I can't seem to get results for: 但是,我似乎无法获得以下结果:

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

ERB will output a plain string. ERB将输出一个纯字符串。 JS needs inverted commas around a string for it to be recognized. JS需要在字符串前后加上逗号以使其能够被识别。 You have missed them on your console.log() statement. 您已经在console.log()语句中错过了它们。

Change it to: 更改为:

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

You may also find the raw helper useful. 您可能还会发现raw帮助程序很有用。 This will call .to_s and .html_safe on any erb output: 这将在任何erb输出上调用.to_s.html_safe

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

Read more about html_safe here . 在此处阅读有关html_safe更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM