Rails:如何根据条件显示包含或不包含链接的块(link_to_if)

Die*_*ngs 8 ruby-on-rails link-to

我有一个复杂的标签块(<h3>,, <p>...),我想根据条件使用链接呈现或没有链接.

我知道link_to_if这样的作品:

<% link_to_if condition, name, path %>
Run Code Online (Sandbox Code Playgroud)

如果条件false只是将呈现的名称.

我知道的link_to&block:

<% link_to path do %>
  [complex content]
<% end %>
Run Code Online (Sandbox Code Playgroud)

我想要两者的结合.如果条件是,则link_to_if接受a 的语句&block,以便在没有链接的情况下呈现块false.不幸的是,link_to_if声明的&block作品不像link_to声明:(

有没有人对我提出建议?任何帮助都非常感谢

klu*_*ump 23

我为此写了自己的帮手:

   def link_to_if_with_block condition, options, html_options={}, &block
     if condition
       link_to options, html_options, &block
     else
       capture &block
     end
   end
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它:

<%= link_to_if_with_block true, new_model_path { "test" } %>
<%= link_to_if_with_block true, new_model_path do %>
  Something more complicated
<% end %>
Run Code Online (Sandbox Code Playgroud)