yield if content, render something otherwise (Rail

2019-04-05 03:02发布

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

How can you accomplish this:

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

Or even:

<%= 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.

In the second case:

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

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.

Thanks!

3条回答
太酷不给撩
2楼-- · 2019-04-05 03:42

How about something like this?

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

Inspiration from this SO question

查看更多
乱世女痞
3楼-- · 2019-04-05 03:43

Try this:

# app/helpers/application_helper.rb
def yield_or(name, content = nil, &block)
  if content_for?(name)
    content_for(name)
  else
    block_given? ? capture(&block) : content
   end
end

so you could do

<%= yield_or :something, 'default content' %>

or

<%= yield_or :something do %>
    block of default content
<% end %>

where the default can be overridden using

<%= content_for :something do %>
    overriding content
<% end %>
查看更多
女痞
4楼-- · 2019-04-05 03:56

I didn't know you could use content_for(:content_tag) without a block and it will return the same content as if using yield(:content_tag).

So:

def yield_or_render(content, template)
  content_for?(content) ? content_for(content) : render(template)
end
查看更多
登录 后发表回答