开发者

In Rails 3: Can a template image be associated with the view that's being displayed?

Sorry, I'm very new at Rails so I'll try to be as specific as I can be.

In my template I have a large "header" style开发者_JS百科 image. I would like to swap that image out for another image that is associated with the view that is being displayed. Maybe this can be done using a helper? I don't even know where to begin with this.

I know I could make a bunch of template pages and load each of them with the desired view, but I think thats a lot of repeated lines of code to load when I simply want to swap one image. Does anyone have an idea?


There are a few options depending on your needs. The first thing that comes to my head is to create a couple of helper methods. One to call from your custom views and one to call from your global layout.

For example, create a file app/helpers/layout_helper.rb

module LayoutHelper
  def header_image_tag
    @header_image ||= 'whatever-my-default-image-is.png'
    image_tag @header_image
  end

  def header_image(image_path)
    @header_image = image_path
  end
end

In your layout file... e.g app/views/application.html.erb. Something like:

<div id='banner'>
  <%= header_image_tag %>
</div>

In your individual view files that you don't want the default image:

<% header_image 'other-image.png' %>

That should get you started. You may want to allow the header_image_tag to take some options to pass onto the image_tag, or set some defaults that can be overridden.

The other thing you can take advantage of is content_for and yield blocks.

Example... in your custom views, you could put something like this at the top of your view:

<% content_for :banner do %>
  <%= image_tag 'blah.png' %>
<% end %>

And in your layout

<div id='banner'>
  <%= yield :banner || image_tag 'my-default.png' %>
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜