【问题标题】:Yielding content_for with a block of default content使用默认内容块生成 content_for
【发布时间】:2011-11-16 14:26:42
【问题描述】:

我们的 Rails 项目大量使用 content_for。但是,如果没有使用 content_for 定义任何内容,我们经常需要呈现默认内容。为了可读性和可维护性,将此默认内容放在一个块中是有意义的。

我们在 Rails 2.3 中创建了一个辅助方法,现在我们为 Rails 3 重构了它(如下所示)。

这两个助手都工作得很好,但我想知道是否有更简洁的方法可以在 Rails 3 中实现相同的目标。

导轨 2.3:

def yield_or(name, content = nil, &block)
  ivar = "@content_for_#{name}"

  if instance_variable_defined?(ivar)
    content = instance_variable_get(ivar)
  else
    content = block_given? ? capture(&block) : content
  end

  block_given? ? concat(content) : content
end

这对于做这样的事情很有用:

<%= content_for :sidebar_content do %>
    <p>Content for the sidebar</p>
<% end %>

<%= yield_or :sidebar_content do %>
    <p>Default content to render if content_for(:sidebar_content) isn't specified</p>
<% end %>

为 Rails 3 重构:

def yield_or(name, content = nil, &block)
  if content_for?(name)
    content_for(name)
  else
    block_given? ? capture(&block) : content
  end
end

【问题讨论】:

  • 可爱的小帮手(“为 Rails 3 重构”)

标签: ruby-on-rails-3


【解决方案1】:

这可以使用 content_for 完全在视图中完成吗?方法。

<% if content_for?(:sidebar_content) %>
  <%= yield(:sidebar_content) %>
<% else %>
  <ul id="sidebar">
    <li>Some default content</li>
  </ul>
<% end %>

【讨论】:

  • 确实可以,如上面“Refactored for Rails 3”所示。但是,如果可以避免的话,我真的很喜欢不必在视图中进行分支,这就是我编写 yield_or 助手的原因。真的只是见仁见智。不过感谢您的回答!
  • 我想我不太确定你在问什么。
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 2020-02-01
  • 1970-01-01
  • 2021-04-04
  • 1970-01-01
相关资源
最近更新 更多