【问题标题】:Rails - How can I detect if the content_for content was provided?Rails - 如何检测是否提供了 content_for 内容?
【发布时间】:2010-04-25 08:07:37
【问题描述】:

我想检测是否在我的模板中为 content_for 标签提供了内容,如果没有返回默认值:

<title>
  <% if content_is_provided -%>
    <%= yield :title -%>
  <% else -%>
    404 - Page Unknown
  <% end -%>
</title>

有什么简单的方法可以检测到这一点吗?我试过&lt;% if :title -%&gt; 但这并没有多大作用。谢谢。

【问题讨论】:

    标签: ruby-on-rails templates erb


    【解决方案1】:

    您可以进一步简化代码:

    def content_exists?(name)
      return instance_variable_get("@content_for_#{name}")
    end
    

    【讨论】:

      【解决方案2】:

      试试这个:

      <title>
        <%= yield :title || "404 - Page Unknown" -%>
      </title>
      

      【讨论】:

      • 可悲的是,这似乎对我不起作用(没有标题呼应)。感谢您的帮助!
      【解决方案3】:

      在旧的 Rails 2.1.1 中,

      <%= (yield :title) || default_title %>
      

      为我工作。

      【讨论】:

        【解决方案4】:

        在对 content_for 代码进行了一番挖掘之后,我通过创建一个辅助方法找到了一个可行的解决方案:

        def content_exists?(name)
          return true if instance_variable_get("@content_for_#{name}")
          return false # I like to be explicit :)
        end
        

        在视图中:

        <% if content_exists?(:title)-%>
          <%= yield :title %>
        <% else -%>
          404 - Page Unknown
        <% end -%>
        

        这似乎正在工作,目前(Rails 2.3.5)。

        【讨论】:

          【解决方案5】:

          另一种方法

          'common/top_status') %>

          【讨论】:

            猜你喜欢
            • 2023-03-29
            • 2015-03-05
            • 1970-01-01
            • 2019-07-05
            • 1970-01-01
            • 2017-11-24
            • 1970-01-01
            • 1970-01-01
            • 2010-12-12
            相关资源
            最近更新 更多