【问题标题】:Rails 4: properly using content_for/rendering partialsRails 4:正确使用 content_for/rendering partials
【发布时间】:2014-04-09 08:29:16
【问题描述】:

我以前从未使用过content_for,但它似乎很有帮助。

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

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

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

<%= render "header" %> 在产品index 页面上,但在标题上方有一个小边距:所以在使用检查元素时,products.css.scss 页面的正文中似乎有一个边距:实际上有products.css.scss 中的 margin-top 值为 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>

【问题讨论】:

    标签: css ruby-on-rails rendering


    【解决方案1】:

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

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

    根据我的经验,content_for 从代码的角度来看是无关紧要的 - 它只存储您告诉它的内容。因此,您的 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

    【讨论】:

    • 嗨 Rich,我非常感谢这个非常详细的答案,但我只是最终更改了 header 部分的 html 类/ID(我发誓我昨晚尝试过但没有成功),一切似乎好的。可能不是最简洁的方法,但现在可以。
    猜你喜欢
    • 2013-01-03
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 2010-10-03
    • 2018-07-25
    • 1970-01-01
    • 2014-10-20
    相关资源
    最近更新 更多