Ruby-on-rails Rails 检查 yield :area 是否在 content_for 中定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/193838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:44:18  来源:igfitidea点击:

Rails check if yield :area is defined in content_for

ruby-on-railslayoutyield

提问by William Yeung

I want to do a conditional rendering at the layout level based on the actual template has defined content_for(:an__area), any idea how to get this done?

我想根据已定义的实际模板在布局级别进行条件渲染content_for(:an__area),知道如何完成此操作吗?

回答by gudleik

@content_for_whateveris deprecated. Use content_for?instead, like this:

@content_for_whatever已弃用。content_for?改为使用,如下所示:

<% if content_for?(:whatever) %>
  <div><%= yield(:whatever) %></div>
<% end %>

回答by efalcao

not really necessary to create a helper method:

创建辅助方法并不是真正必要的:

<% if @content_for_sidebar %>
  <div id="sidebar">
    <%= yield :sidebar %>
  </div>
<% end %>

then of course in your view:

那么当然在你看来:

<% content_for :sidebar do %>
  ...
<% end %>

I use this all the time to conditionally go between a one column and two column layout

我一直使用它来有条件地在一列和两列布局之间切换

回答by gregwinn

<%if content_for?(:content)%>
  <%= yield(:content) %>
<%end%>

回答by Nick

Can create a helper:

可以创建一个助手:

def content_defined?(var)
  content_var_name="@content_for_#{var}"    
  !instance_variable_get(content_var_name).nil?
end

And use this in your layout:

并在您的布局中使用它:

<% if content_defined?(:an__area) %>
  <h1>An area is defined: <%= yield :an__area %></h1>
<% end %>

回答by Enrico

I'm not sure of the performance implications of calling yield twice, but this will do regardless of the internal implementation of yield (@content_for_xyz is deprecated) and without any extra code or helper methods:

我不确定两次调用 yield 对性能的影响,但是无论 yield 的内部实现如何(@content_for_xyz 已弃用)并且没有任何额外的代码或辅助方法,这都将起作用:

<% if yield :sidebar %>
  <div id="sidebar">
    <%= yield :sidebar %>
  </div>
<% end %>

回答by William Yeung

Ok I am going to shamelessly do a self reply as no one has answered and I have already found the answer :) Define this as a helper method either in application_helper.rb or anywhere you found convenient.

好的,我将无耻地做一个自我回复,因为没有人回答,我已经找到了答案:) 在 application_helper.rb 或任何您觉得方便的地方将其定义为辅助方法。

  def content_defined?(symbol)
    content_var_name="@content_for_" + 
      if symbol.kind_of? Symbol 
        symbol.to_s
      elsif symbol.kind_of? String
        symbol
      else
        raise "Parameter symbol must be string or symbol"
      end

    !instance_variable_get(content_var_name).nil?

  end