Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a link_to_if with block only if condition is met?

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?

like image 516
mabu Avatar asked Dec 23 '22 09:12

mabu


1 Answers

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?) %>
like image 125
spickermann Avatar answered Jan 05 '23 01:01

spickermann