Rails 4:正确使用content_for /呈现部分

时间:2014-04-09 08:29:16

标签: css ruby-on-rails rendering

我之前从未使用content_for,但它似乎非常有用。

我可能会让它变得更加艰难,但目标是:

在产品#index页面上设置自定义标题。

目前,我已将该标头设置为products文件夹中的部分(_header.html.erb)。我在打电话

产品<%= render "header" %>页面上的

index,但标题上方略有边缘:因此,在使用Inspect Element时,products.css.scss的正文中似乎存在边距page:在products.css.scss中实际上有一个margin-top值为40px,但为什么在app/views/products/转移到标题部分?

我试图以干净的方式理解这一点,所以我没有完全令人作呕的旋风。似乎在这里使用content_for方法是可行的(但对于类似的东西可能过于复杂?),但我觉得因为我的_header.html.erb文件具有以下内容它应该没问题

  <%= stylesheet_link_tag "header" %>
  <div id="transparent-box">
    <div class="logo-red"></div>
    <div class="banner-items">
      <%= link_to 'About', '#', :class => 'banner-item' %>
      <%= link_to 'Shop', '/products', :class => 'banner-item' %>
      <%= link_to 'Contact', '#', :class => 'banner-item' %>
      <%= link_to 'Cart', '/products/current', :class => 'banner-item' %>
    </div>
  </div>

1 个答案:

答案 0 :(得分:0)

content_for :____基本上存储了一组HTML,可以在布局的另一部分(精心设计的变量)中调用,如described in the documentation

  

调用#content_for会在标识符中存储标记块   以后用。为了在其他模板中访问此存储的内容,   帮助模块或布局,您将传递标识符作为   content_for的参数

根据我的经验,content_for对代码的观点漠不关心 - 它只存储你告诉它的内容。因此,使用content_for时,您的CSS问题并不是真正的问题,但我认为您调用header文件的方式存在问题


<强>修正

根据您的说明,我认为您对render partial: "header"的调用可能会干扰整个文档中的CSS。请记住,仅仅因为你调用部分并不意味着它没有CSS样式 - 你的类仍然会有样式,这可能在你的CSS中定义了

为什么不试试这个:

#app/layouts/application.html.erb
<%= content_for :header %>

#app/controllers/application_controller.rb
include ApplicationHelper

#Content_For
def view_context
    super.tap do |view|
        (@_content_for || {}).each do |name,content|
            view.content_for name, content
        end
    end
end

def content_for(name, content) # no blocks allowed yet
    @_content_for ||= {}
    if @_content_for[name].respond_to?(:<<)
        @_content_for[name] << content
    else
        @_content_for[name] = content
    end
end

def content_for?(name)
    @_content_for[name].present?
end

#app/controllers/products_controller.rb
def index
    content_for :header, render partial: "products/header" #-> not sure if syntax is right
end

如果

中有内容,则会加载header content_for