Rails 3 - yield return or callback won't call in view <%= yield(:sidebar) || render('shared/sidebar') %>

纵饮孤独 提交于 2019-12-03 13:39:57

Ryan Bates from railscasts.com shows in Episode #227 - Upgrading to Rails 3 Part 3 a solution with content_for?() (video playback at 2:45 Min)

I think, that's the way we should use it:

content_for?(:sidebar) ? yield(:sidebar) : render("shared/sidebar")

I tested this out and it looks like Rails 3 is returning empty string instead of nil. So, unless they change this before the final release you will have to modify your code to see if the value is blank instead of just nil.

(sidebar = yield(:sidebar)).present? ? sidebar : render("shared/sidebar")
Pixoo

I usually set my site title with:

<title><%= ['My Site', yield(:title)].compact.join(' - ') %></title>

Due to this change, it would be ugly to add some conditions, so I created a helper like this:

module ApplicationHelper
    def nil_empty(str)
        str.blank? ? nil : str
    end
end

Then I can do something like:

<title><%= ['My Site', nil_empty(yield :title)].compact.join(' - ') %></title>

It's still ugly, but a little bit less :)

Thanks Mike Dotterer. I took your idea and modified it a bit.

yield(:sidebar).presence || render("shared/sidebar")

object.presence is equivalent to object.present? ? object : nil

provide vs content_for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!