Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.


Solution 2:

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.


Post a Comment for "How Do I Access A Rails Variable That Is Only Accessible To A Partial?"