css - rails 4 : properly using content_for/rendering partials

标签 css ruby-on-rails rendering

我从来没有用过content_for之前,但它似乎很有帮助。

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

在 products#index 页面上有一个自定义 header 。

目前,我将该 header 设置为产品文件夹中的部分 ( _header.html.erb)。我在打电话

<%= render "header" %>关于产品index页面,但标题上方有一个小边距:因此在使用 Inspect Element 时,products.css.scss 的正文中似乎有一个边距链接。页面:实际上有一个margin-top products.css.scss 中 40px 的值,但到底为什么要将其转移到 app/views/products/ 中的标题部分? ?

我试图以简洁的方式理解这一点,这样我就不会对 CSS 感到厌恶。似乎使用 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>

最佳答案

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

Calling #content_for stores a block of markup in an identifier for later use. In order to access this stored content in other templates, helper modules or the layout, you would pass the identifier as an argument to content_for

根据我的经验,content_for 从代码的 Angular 来看是无关紧要的 - 它只存储您告诉它的内容。因此,您的 CSS 问题实际上并不是 content_for 的使用问题,而是我认为您如何调用 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 block

关于css - rails 4 : properly using content_for/rendering partials,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22956874/

相关文章:

ruby-on-rails - 如何仅修改内存中的 zip 文件?

ruby-on-rails - form_tag 的 date_select 与 form_for 的等效项是什么?

ruby-on-rails - Rails - 单个表单上多个模型的用户输入 - 如何

video - 视频动态渲染有多难?

android - 将叠加图形渲染到摄像机视频中

css - CSS中容器的扩展宽度

html - <h1>没有从其容器继承font-weight

c++ - 遍历图像行和列

css - 如何创建具有相反 flex 底部的 div

html - CSS 使我的背景以颜色开始并以另一种(相似的)颜色背景图像 : linear-gradient 结束