简体   繁体   中英

Javascript variable inside Erb Tag

I am trying to access a javascript variable in js.erb file inside erb tag. for example

my_variable = window.location.pathname.split("/")[2];

@project = Project.find(my_variable)

So is there a way to pass 'my_variable' in the 'find' helper.

An alternative solution would be to get the URI on the rails side, fetch the project(s) and parse them to JSON - reparse them in js.erb and send the contents of the file to the client.

This way you do not have to execute JS on your server and you'll still have the project within the JS file you need.

This answer explains how to get the request URI for different rails versions.

For Rails 3.2 or Rails 4+

You should use request.original_url to get the current URL.

This method is documented at http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url , but if you're curious, the implementation is:

 def original_url base_url + original_fullpath end 

For Rails 3:

You can write "#{request.protocol}#{request.host_with_port}#{request.fullpath}" , since request.url is now deprecated.

EDIT (20-11-2015)

Since you seem to be requiring a specific segment of the url, you could mimic the JS implementation with ruby easily by simply calling original_url.split('/')[2]

You can easily do with https://github.com/sstephenson/execjs , as you can see

require "execjs"
ExecJS.eval "'red yellow blue'.split(' ')"

You can get the returning value easily.

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