开发者

Creating a generic HTML header with blocks in Rails

What I want is to do something like this in my views:

<% page_header "Your Posts" do %>
    <div class="add">
      <%= link_to 'Add a new post', new_posts_path %>
    </div>
<% end %>

And have the HTML render something like this:

<div class="page_header">
  <h2>Your Posts</h2>
  <div class="add">
    <a href="/posts/new">Add a new post</a>
  </div>
</div>

However, sometimes I don't want to have any extra content and just have the rendered HTML be:

<div class="page_header">
  <h2>Your Posts</h2>
</div>

Instead of having two methods I want to use a block to render the extra content if it's given, or just the header if it's not; this way I can use a generic call in all of my views to keep my code DRY.

I have the following code in my Application Helper, but it doesn't seem to be rendering anything:

# Renders a div for the page header with an H2 tag representing the page title
# If a block is provided, renders that content within the page header DIV
def page_header(title, &block)
  concat(content_tag(:div, :class => "page_header") do
    content_tag(:h2, title) 
  end)
  block.call if block_given?
end

However, this doesn't work. When I give a block, it renders properly. Without the block, though, it doesn't render anything, not even the defa开发者_开发知识库ult .

I'm missing something simple to fix this, but I'm not sure what.


Shouldn't the block call be inside the content_tag?, like so:

# Renders a div for the page header with an H2 tag representing the page title
# If a block is provided, renders that content within the page header DIV
def page_header(title, &block)
  concat(content_tag(:div, :class => "page_header") do
    content_tag(:h2, title) +
    block_given? ? block.call : '' 
  end)

end


You can do something like this

def page_header(title, &block)
  concat( render :partial=>"shared/page_header",:locals=>{:title=>title,:body=> capture(&block)})
end

inside the partial _page_header.erb

 <div class='page-header'>
  <h2> <%= title %> </h2>
   <%= body %>
 </div>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜