代码之家  ›  专栏  ›  技术社区  ›  Wayne Molina

在Rails中创建带有块的通用HTML标头

  •  1
  • Wayne Molina  · 技术社区  · 15 年前

    在我看来,我想做的是这样的事情:

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

    并让HTML呈现如下内容:

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

    但是,有时我不希望有任何额外的内容,只希望呈现的HTML是:

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

    # 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
    

    然而,这不起作用。当我给出一个块时,它会正确渲染。但是,如果没有块,它不会渲染任何东西,甚至不会渲染默认值。

    我错过了一些简单的方法来解决这个问题,但我不确定是什么。

    2 回复  |  直到 15 年前
        1
  •  1
  •   Tilendor    15 年前

    # 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
    
        2
  •  -1
  •   Rishav Rastogi    15 年前

    你可以这样做

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

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