I want to render a link only if the condition is met with the following link_to_if
:
<%= link_to_if policy(@user.add?), new_entry_path(), class: 'btn' do %>
<%= glyphicon("plus") %>
<% end %>
The block with the glypicon("plus")
helper method should also only be called if the condition of the link_to_if
is met. With the code above the block is always called, no matter whether the condition is true or false.
How do I create the link and its inner content only if the condition returns true?
Just use a simple if
and a link_to
:
<% if policy(@user.add?) %>
<%= link_to new_entry_path, class: 'btn' do %>
<%= glyphicon('plus') %>
<% end %>
<% end %>
Or you might want to consider a view helper method like this:
def link_to_add(url)
link_to(glyphicon('plus'), url, class: 'btn')
end
Which can be used in to view like:
<%= link_to_add(new_entry_path) if policy(@user.add?) %>
Or more generic:
def icon_link(icon, url)
link_to(glyphicon(icon), url, class: 'btn')
end
Which can be used in to view like:
<%= icon_link('plus', new_entry_path) if policy(@user.add?) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With