简体   繁体   中英

Access Rails global constant in Javascript / jQuery

My setup: Rails 3.0.9, Ruby 1.9.2, jQuery 1.6.2

Rails

constants.rb (initializer file)

DEFAULT_REPLY = "Add a reply..."

Rails

index.html.erb 

<%= javascript_include_tag 'reply' %>
...(rest of view code)...

reply.js

$(function() {
 var default_reply = <%= h DEFAULT_REPLY -%>;
 ...(rest of jQuery code)...
});

This throws an error Uncaught SyntaxError:Unexpected token %= , I tried to enclose it in quotes like var default_reply = '<%= h DEFAULT_REPLY -%>' and it output the value as is, meaning default_value has the value of <%= h DEFAULT_REPLY -%>' which is clearly not what I intended. What am I doing wrong?

EDIT Given the feedback, I have reconsidered and is now using a local variable and jQuery to pull the value from the textarea upon page load.

You need to add .erb to the end of your .js file, along with add the quotes around the string.

The name of your javascript file should be reply.js.erb.

Currently, your .js file is not being run through rails, and is being served statically. That is why when you put the quotes around the string, it output the string '<%= h DEFAULT_REPLY %>' instead of the correct text.

I'd strongly recommend against this approach but I think you're confusing two things here.

Assuming reply.js is in public/javascripts/reply.js , this is a static JS file that is served up by your server. You cannot put any dynamic ("server side") code in here as the file is not evaluated in any manner, just passed back statically.

If you want a global JS variable to use in your files, you'd need to do assign it in your layout file app/views/layouts/application.html.erb or in your action files ( index.html.erb , show.html.erb , etc).

Any ERB file is evaluated before returning it, so you could put

<script type='text/javascript'>
  $(function() {
   var default_reply = "<%= escape_javascript DEFAULT_REPLY %>";
  });
</script>

above the <%= yield %> statement of your layout file.

Again, I'd STRONGLY recommend against this approach but if that's why you need, I think this will solve it.

It sounds like you named your view template incorrectly, does it end in .html.erb? If not, it won't evaluate the ERB fragment you pasted.

Once you fix that, you can embed what you want with the following ERB code:

$(function() {
 var default_reply = "<%= h DEFAULT_REPLY -%>";
 ...
});

If it is a rails 3 App why are you using that syntax? try:

var default_reply = <%= DEFAULT_REPLY %>;

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