开发者

link_to_if Why does it show the Link Title if false?

Why does link_to_if show the link title if the condition is false?

I'm using it on a DELETE, and if the condition is false, Rails shows delete but it isn't linked. I don't want DELETE to show up if it's false.

Is there a setting or another helper 开发者_运维知识库for that?

Thank you


If you just want the link to disappear completely, just use an 'if' around the link_to, rather than link_to_if.

<% if condition %>
  <%= link_to ... %>
<% end %>

If you want something else to appear when the condition is not true, you can pass a block to render instead. Having said that, from a stylistic perspective, I think I prefer 'if' 'else' to the block syntax - it's less confusing, at least to my eye.

Block syntax:

<%= link_to_if(condition, "Link Title", dest ) { link_to( "Alt Title", alt_dest ) } %>

If/else syntax:

<% if condition %>
  <%= link_to "Link Title", dest %>
<% else %>
  <%= link_to "Alt Title", alt_dest %>
<% end >

For more information see the documentation for UrlHelper.


You can take advantage of the block and just use instead of the if/else structure:

<%= link_to_if(message.user, 'Poster', message.user){} %>

In this case, since the block is empty, it won't show anything if the condition is false.


For more information -

The complete syntax of link_to_if is-

link_to_if(condition, name, options = {}, html_options = {}, &block)

If you go through the source, you'll find that if the condition is false, it'll try to execute the given block & when a block is not given it'll just return the name.

The trick to avoid displaying name is to just specify an empty block as explained by @JoaoDaniel-

<%= link_to_if(message.user, 'Poster', message.user, class: 'htmlClass') {} %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜