如何在 js.erb 中使用 Ruby 代码? [英] How to use Ruby code inside js.erb?

查看:53
本文介绍了如何在 js.erb 中使用 Ruby 代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 js.erb 文件代码中使用 escape_javascript 在模态内渲染部分:

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

推荐答案

ERB 将输出一个纯字符串.JS 需要在字符串周围加上引号才能识别它.您在 console.log() 语句中遗漏了它们.

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.

改为:

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

您可能还会发现 raw 助手很有用.这将在任何 erb 输出上调用 .to_s.html_safe:

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

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

阅读有关 html_safe 的更多信息此处.

Read more about html_safe here.

这篇关于如何在 js.erb 中使用 Ruby 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆