Rails:如何根据条件显示带或不带链接的块 (link_to_if) [英] Rails: How can I show a block with or without a link based on a condition (link_to_if)
问题描述
我有一个复杂的标签块(、
、...)根据条件链接它.
I have a complex block of tags (<h3>
, <p>
, ...) that I want to render with a link or without a link around it based on a condition.
我知道 link_to_if
是这样工作的:
I know about link_to_if
that works like that:
<% link_to_if condition, name, path %>
如果条件为 false
,则只会呈现名称.
if the condition is false
only the name will be rendered.
而且我知道 link_to
和 &block
:
<% link_to path do %>
[complex content]
<% end %>
我想要两者的结合.接受 &block
的 link_to_if
语句,如果条件为 false
,则块将在没有链接的情况下呈现.不幸的是,带有 &block
的 link_to_if
语句与 link_to
语句不同:(
I want a combination of both. A link_to_if
statement that accepts a &block
, so that the block will be rendered without a link around it, if the condition is false
. Unfortunately the link_to_if
statement with a &block
works not like the link_to
statement :(
有人给我建议吗?非常感谢任何帮助
Does anyone have suggestion for me? Any help is highly appreciated
推荐答案
我为此编写了自己的帮助程序:
I wrote my own helper for this:
def link_to_if_with_block condition, options, html_options={}, &block
if condition
link_to options, html_options, &block
else
capture &block
end
end
你可以这样使用它:
<%= link_to_if_with_block true, new_model_path { "test" } %>
<%= link_to_if_with_block true, new_model_path do %>
Something more complicated
<% end %>
这篇关于Rails:如何根据条件显示带或不带链接的块 (link_to_if)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!