Skip to content

Gaining access to the rails variables inside js file #1684

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
ytbryan opened this issue Sep 4, 2018 · 5 comments
Closed

Gaining access to the rails variables inside js file #1684

ytbryan opened this issue Sep 4, 2018 · 5 comments

Comments

@ytbryan
Copy link
Contributor

ytbryan commented Sep 4, 2018

Hi folks,

does anyone know how do I access the rails variables via erb inside a .js file. I am not looking for an alternate solution like using the gon rubygem.

From #1256, I know I can access the ActionController' helpers using:

<% helper = ActionController::Base.helpers %>
<% helpers.asset_pack_path('rails.png') %>

How do I print the rails variable (@something) of my index action of Actioncontroller, inside the js.erb?

For instance,

#inside PagesController.rb
def index
@something = "something" 
end
//packs/something.js.erb
console.log("<%= @something %>")

What am I missing here? Appreciate any pointers. Thank you!

@haffla
Copy link
Contributor

haffla commented Sep 5, 2018

In a standard (non-Webpacker) .js or .js.erb file you cannot access controller instance variables either as far as I know.

If you cannot use gon, I guess you have to do it manually and set the variables in the view and access them then in your Javascript.

@ytbryan
Copy link
Contributor Author

ytbryan commented Sep 5, 2018

Yup, I am not looking at non-webpacker setup but mainly looking at app/javascript/packs/*js.erb

I was hoping that Rails' ujs has something available for direct usage.

@gauravtiwari
Copy link
Member

Not sure if that's easily doable unless you extend the ActionController::Base.helpers with your own set of helpers, which is a bit repetitive and probably not intuitive if you want to share instance variables - https://github.com/rails/webpacker/blob/master/lib/webpacker/railtie.rb#L64.

Is it not possible to use data-attrs i.e. declaring data-attrs in the view and reading it back in JS?

<div data-attrs="{something: "foo"}" id="foo">
</div>
const foo = JSON.parse(document.getElementById('foo').dataset.attrs);
foo.something

@sharang-d
Copy link
Contributor

@ytbryan Did that work for you? Can we close this?

@anon987654321
Copy link

If I may ask, what's really the point of Erb in JS if we can't access Rails variables?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants