1

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

asked Oct 4, 2014 at 14:33
4
  • You have to make it an erb file. I'd argue against doing so, though. Commented Oct 4, 2014 at 14:35
  • I've tried to add the js.erb suffix but then the include doesn't work. Any clue?. Or any other option?. Commented Oct 4, 2014 at 14:36
  • Do you really need to include it in <head>? What's the problem with require_tree . in application.js? Commented Oct 4, 2014 at 14:42
  • It's a page specific JS. With require_tree . it will include it in every view, it's an overhead I don't want. I could add the javascript_include_tag in the body, but does it make any difference?. Commented Oct 4, 2014 at 14:45

1 Answer 1

1

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.

answered Oct 4, 2014 at 14:58
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.