Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are controller instance variables accessible in the asset pipeline?

Given a file posts.js.coffee.erb in the asset pipeline, I can do this

  alert "<%= Rails.env %>"

but what about accessing instance variables defined in the controller?

  alert "<%= @posts.to_json %>"
like image 713
Gavin Avatar asked Dec 05 '25 01:12

Gavin


2 Answers

You can't. I was trying to add theming functionality to a blog application, and it turns out that it won't see the application helper methods or instance variables.

What I have done instead is create css view for the show action in themes, something like show.css.erb, which will be accessed via url like /themes/black.css

The same can be done with javascript, so if you need a specific javascript view just create a view for posts.js.erb

This technique is not even new in rails. I remember someone asking in twitter if you could do something like that in asp.net mvc back in 09

Additionally you will need to have your controller respond to that format, the following is a snippet from the app I was working on.

def show
  @theme = Theme.find(params[:id])

  respond_to do |format|
    format.html
    format.css
  end
end
like image 171
jgarcia Avatar answered Dec 06 '25 15:12

jgarcia


I think you need to alert this from the view, not a static js file.

like image 26
nir0 Avatar answered Dec 06 '25 15:12

nir0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!