small extension to link_to_if

Hi

I frequently use link_to in the context of conditional statement,

What do you think about a link helper that return nil when the condition is false

ex:

condtional = nil || false

<%= link_to_if conditional, an_url, allow_hide: true %> # => nil

or

<%= link_to_if! conditional, an_url %> # => nil

Thank you!

What about using link_to_unless ?

You mean like these?

http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to_if

http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to_unless

No, currently link_to_if(unless) returns the name in the false case.

Angelo,

thank you for your suggestion, but is not this already possible using a normal if statement?


<% if conditional %>

<%= link_to ... %>

<% end %>

I see a point to having a helper if you use this same pattern in a lot of places. But, for this case, I recommend to define a helper in your application.

Sure,

the purpose of my example above is only to introduce this.

When you have a sidebar partial with 3 or more dinamic menu, ex:


<% if user_role.admin? %>

<%= link_to an_url,.. do %>

Menu Label for admin

<% end  %>

<% end %>

<% if user_role.user?%>

<%= link_to an_url,.. do %>

Menu Label for user

<% end  %>

<% end %>

<% if user_role.guest?%>

<%= link_to an_url,.. do %>

Menu Label for gues

<% end  %>

<% end %>

Whit this helper we can have the following code:


<%= link_to_if! user_role.admin? an_url,.. do %>

Menu Label for admin

<% end  %>

<%= link_to_if! user_role.user? an_url,.. do %>

Menu Label for user

<% end  %>

<%= link_to_if! role.guest?, an_url,.. do %>

Menu Label for guest

<% end  %>

In other word has the same role of link_to_if(unless) but allows to get to not display nothing in the conditional false case

Maybe would be better if you continue to do what you are doing or define a helper in your side.

For your use case you may have a <div> that can’t be seem by a normal users, so link_to_if! will not help you, and I don’t see us adding content_for_if or form_tag_if inside Rails.

You can already achieve basically the same functionality with Ruby and conditional modifiers:

<%= link_to an_url,… do %>

Menu Label for admin

<% end if user_role.admin? %>

<%= link_to an_url,… do %>

Menu Label for user

<% end if user_role.user? %>

<%= link_to an_url,… do %>

Menu Label for gues

<% end if user_role.guest? %>

I don’t think there’s need for new methods in this scenario. Thanks! <3

Although it doesn’t change things much, I would write this as: <%= link_to “Menu Label for Admin”, a_url if user_role.admin? %>

This is mostly because I can’t wrap my head around do…end…if, and it looks shorter.

I’ll admit that link_to_if is a bit confusing the first time you encounter it, but i got used to it after a while. I expected link_to_if to literally be: `link_to(*args) if condition’.

That being said, I’ve never actually used link_to_if, because I haven’t found a use case for it personally.