2

Good day, i have this kind of code:

= link_to some_url do
  PLENTY OF MARKUP HERE

Now i need to make this link optional, so if condition is not met i need plain MARKUP to be printed, so first anti-DRY solution:

- if condition
  = link_to some_url do
    PLENTY OF MARKUP HERE
-else
  PLENTY OF MARKUP HERE REPEATED :(

Another solution if to put PLENTY OF MARKUP into partial, so i winder if where is another simple solution without partial ? I tried this one:

= link_to_if condition?, some_url do
  PLENTY OF MARKUP HERE

but unfortunately link_to_if does not work as expected here.

4

2 回答 2

1

link_to_if与 .相比,将块用于不同的目的link_to。所以它不能做你想做的事。

你可以定义自己的助手来做你想做的事。

如果您只需要这样做几次,而不是使用自定义帮助程序,您可以将块的结果 (the PLENTY OF MARKUP) 保存到局部变量中,以便您轻松重复使用它。例如:

- plentyofmarkup = do
  PLENTY OF MARKUP HERE

- if condition
  = link_to (raw plentyofmarkup), some_url
- else
  = raw plentyofmarkup

或者:

= link_to_if condition, (raw plentyofmarkup), some_url

请注意,该raw函数用于阻止 Rails 自动转义字符串。

要定义您自己的辅助方法,请尝试:

def link_to_if_do condition, options = {}, html_options = {}
  blockresult = yield
  link_to_if condition, blockresult, options, html_options
end
于 2012-09-06T08:46:13.050 回答
0

您总是可以编写自己的条件链接帮助器,并将其放在 application_helper 中:

def conditional_link_to( condition, url, options = {}, html_options = {}, &block ) do
  if condition
    link_to(name, options, html_options, &block)
  else
    if block_given?
      block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
    else
      name
    end
  end
end

这主要取自link_to_unless,但经过修改以将块传递给 link_to。我没有测试过这个,但它应该足以给你一个想法。:)

于 2012-09-06T08:45:32.210 回答