如果内容则产生,否则渲染(Rails 3) [英] yield if content, render something otherwise (Rails 3)

查看:60
本文介绍了如果内容则产生,否则渲染(Rails 3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经离开 Rails 一段时间了,所以我可能遗漏了一些简单的东西.

I've been away from Rails for a while now, so maybe I'm missing something simple.

你怎么能做到这一点:

<%= yield_or :sidebar do %>
  some default content
<% end %>

甚至:

<%= yield_or_render :sidebar, 'path/to/default/sidebar' %>

在第一种情况下,我正在尝试:

In the first case, I'm trying:

def yield_or(content, &block)
  content_for?(content) ? yield(content) : yield
end

但这会引发未给出块"错误.

But that throws a 'no block given' error.

第二种情况:

def yield_or_render(content, template)
  content_for?(content) ? yield(content) : render(template)
end

这在没有定义内容时有效,但是一旦我使用 content_for 覆盖默认内容,它就会抛出相同的错误.

This works when there's no content defined, but as soon as I use content_for to override the default content, it throws the same error.

我使用了这个 作为起点,但似乎只有在视图中直接使用时才有效.

I used this as a starting point, but it seems it only works when used directly in the view.

谢谢!

推荐答案

这样的事情怎么样?

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

这个问题的灵感

这篇关于如果内容则产生,否则渲染(Rails 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆