smaili
smaili

Reputation: 1235

Adding a conditional block in ERB

I have the following in my ERB layout:

<%# Check for block -%>
<% if content_for?(:layoutBlock) %>
    <%# If so, yield to it -%>
    <%= yield :layoutBlock %>
<%# Otherwise... -%>
<% else %>
    <%# Do stuff -%>
<% end %>

Which essentially checks to see if the view has content for layoutBlock, and if so let it run, otherwise it will execute its own content for layoutBlock.

Is there a way to define some alias that would simplify this to:

<% optionalYield :layoutBlock %>
    <%# Do stuff -%>
<% end %>

Upvotes: 0

Views: 342

Answers (1)

spickermann
spickermann

Reputation: 106792

I would expect that a helper like this would work

# in a helper
def optional_block(block_name, &block)
  concat(content_for(block_name).presence || capture(&block))
end

which could be used in the view like this:

<% optional_block(:layoutBlock) %>
  # Content that is only rendered when content_for(:layoutBlock) is blank
<% end %>

Upvotes: 4

Related Questions