简体   繁体   中英

rails helper - conditionally yield block or fallback

How can I create a helper to yield content in a block OR fallback to something else?

Something like:

def yield_or_fallback
  if item.foo?
    yield
  else
    "bar"
end
<%= item.yield_or_fallback do %>
  "hello"
<% end %>
when item.foo == true
"hello
when item.foo == false
"bar"

The above does not work. How can I accomplish something like this with a helper?

Just pass item to that method

def yield_or_fallback(item)
  if item.foo?
    yield
  else
    "bar"
  end
end

and call it like this

<%= yield_or_fallback(item) do %>
  "hello"
<% end %>

But given that your condition is pretty simple I would prefer to have the view code more explicit:

<%= if item.foo %>
  hello
<% else %>
  bar
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM