8

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

我知道link_to_if这样的工作方式:

<% link_to_if condition, name, path %>

如果条件是false只有名称将被呈现。

我知道link_towith &block

<% link_to path do %>
  [complex content]
<% end %>

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

有人对我有建议吗?非常感谢任何帮助

4

2 回答 2

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

你可以像这样使用它:

<%= link_to_if_with_block true, new_model_path { "test" } %>
<%= link_to_if_with_block true, new_model_path do %>
  Something more complicated
<% end %>
于 2012-04-24T21:21:18.930 回答
4

我只是覆盖了内置方法,因为它们提供的块使用对我们的使用没有多大意义。只需将它添加到帮助程序中,这将使 link_to_if 像 link_to 一样工作。

def link_to_if(*args,&block)
  args.insert 1, capture(&block) if block_given?

  super *args
end
于 2014-09-18T15:19:33.577 回答