How do I access a rails variable that is only accessible to a partial?
Sorry I'm a newbie to Ruby on Rails. I'm very confused about the big picture, so your help would be appreciated.
In my application.html.haml, I call =yield, which takes its output from ranked.html.haml. Now, the latter has access to the rails variable @featured_image.
What I want to do is to get hold of this rails variable @feat开发者_Go百科ured_image on page load, so that I can preload that image and images with ids right after that.
But my window.onload = function() in application.html.haml has no access to @featured_image...
how do I do this??
Thanks!!
As Chris Heald noted, the @featured_image variable is an instance variable on the controller, and you have access to it in your views. To use it from javascript, what you'll basically have to do is write it into your layout or partial somewhere in a script block like this (this is erb, not haml):
<script>
var featured_image="<%= @featured_image %>";
</script>
Obviously, you'll want to add in a check for nil value in @featured_image and handle it in a way that's appropriate for your app, or otherwise ensure that its always set to something. Chris's suggestion to use a helper is also a good one but I wasn't sure it was obvious what the helper would need to do for a newbie.
If @featured_image
is set from a controller, it will be visible to all views in the render pipeline. You just can't necessarily always assume that it's visible, though, since a layout will potentially render many pages, so you'll want to check that it's there before attempting to use it from the layout.
I'd recommend using a helper method to check to be sure it's not nil, and then write out the proper markup. You might also look at content_for
, which lets you mark blocks of markup to be rendered in other parts of the layout.
精彩评论