gpt4 book ai didi

css - rails 4 : properly using content_for/rendering partials

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:11 24 4
gpt4 key购买 nike

我从来没有用过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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com