简体   繁体   中英

Rails ERB Inside Javascript

I'm trying to use some View instance variables inside Javascript .

My JS file is included in the head tag of my HTML . And it's a *.js file in assets/javascript .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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