Css Rails 4:正确使用内容/呈现部分

Css Rails 4:正确使用内容/呈现部分,css,ruby-on-rails,rendering,Css,Ruby On Rails,Rendering,我以前从未使用过content_,但它似乎非常有用 我可能会让这件事变得更加困难,但目标是: 在productsindex页面上具有自定义标题 目前,我在products文件夹中将该标题设置为partial _header.html.erb。我在打电话 在products index页面上,但是在标题上方有一个轻微的边距:因此在使用Inspect元素时,似乎在products.css.scss页面的正文中链接了一个边距:实际上,products.css.scss中有一个边距上限值40px,但究竟

我以前从未使用过content_,但它似乎非常有用

我可能会让这件事变得更加困难,但目标是:

在productsindex页面上具有自定义标题

目前,我在products文件夹中将该标题设置为partial _header.html.erb。我在打电话

在products index页面上,但是在标题上方有一个轻微的边距:因此在使用Inspect元素时,似乎在products.css.scss页面的正文中链接了一个边距:实际上,products.css.scss中有一个边距上限值40px,但究竟为什么要在app/views/products/中将其转移到标题部分

我正试图以清晰的方式理解这一点,这样我就不会有一个令人厌恶的CSS旋风。在这里使用content_作为方法似乎是可行的,但对于类似这样的东西可能过于复杂了,但我觉得既然我的_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>
content_for:___;基本上存储一组HTML,可以在布局的另一部分中调用一个精心设计的变量,如下所示:

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

根据我的经验,content_for从代码的角度来看是无关紧要的——它只存储您告诉它的内容。因此,您的CSS问题实际上不是使用content_的问题,而是如何调用头文件的问题

修理

根据您的描述,我认为您对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

这将为block加载标题内容,如果里面有内容

Hi Rich,我肯定非常感谢这个非常详细的答案,但我只是改变了html类/ID,我发誓我昨晚尝试了,但没有成功,标题部分和所有内容似乎都没有问题。可能不是最简洁的方法,但现在就可以了。