简体   繁体   English

Rails ERB内置JavaScript

[英]Rails ERB Inside Javascript

I'm trying to use some View instance variables inside Javascript . 我试图在Javascript中使用一些View实例变量。

My JS file is included in the head tag of my HTML . 我的JS文件包含在HTMLhead标签中。 And it's a *.js file in assets/javascript . 这是Assets / javascript中* .js文件。

When I try to... 当我尝试...

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

... I get syntax error. ...我收到语法错误。 And if I try to... 如果我尝试...

console.log('<%= @some_instance_variable %>')

... the output is just the string <%= @some_instance_variable %> . ...输出只是字符串<%= @some_instance_variable%> How can I do to obtain the instance variable's actual value?. 如何获取实例变量的实际值? I'd really appreciate any help!. 我将非常感谢您的帮助!

Regards!. 问候!。

You can include it with: 您可以将其包含在:

<%= javascript_include_tag('file_name.js.erb'.sub('.erb', '')) %>

But in fact it's a very ugly solution. 但实际上,这是一个非常丑陋的解决方案。 If you want to use rails variables in JS scripts, use gon gem . 如果要在JS脚本中使用rails变量,请使用gon gem

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

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