[英]Rails HAML conditional link_to
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: 现在,我需要将此链接设置为可选,因此,如果不满足条件,则需要打印普通的MARKUP,因此,第一个抗DRY解决方案:
- 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 ? 如果将
PLENTY OF MARKUP
分为部分内容,则是另一种解决方案,所以如果没有部分内容的另一简单解决方案在哪里,我会绕线吗? 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. 但是很遗憾,
link_to_if
在这里无法正常工作。
link_to_if
uses the block for a different purpose compared to link_to
. 与
link_to
相比, link_to_if
使用该块的目的不同。 So it cannot do what you want. 因此它无法做您想要的。
You can define your own helper to do what you want. 您可以定义自己的助手来完成您想要的事情。
If you only need to do this a few times, instead of using a custom helper, you can instead save the result of a block (the PLENTY OF MARKUP
) to a local variable, to make it easy for you to use it repeatedly. 如果只需要执行几次操作,而不是使用自定义帮助程序,则可以将块的结果(
PLENTY OF MARKUP
)保存到局部变量中,以使您轻松重复使用它。 For example: 例如:
- plentyofmarkup = do
PLENTY OF MARKUP HERE
- if condition
= link_to (raw plentyofmarkup), some_url
- else
= raw plentyofmarkup
Or alternatively: 或者:
= link_to_if condition, (raw plentyofmarkup), some_url
Note that the raw
function is used to stop Rails from escaping the string automatically. 请注意,
raw
函数用于阻止Rails自动转义字符串。
To define your own helper method, try: 要定义自己的帮助器方法,请尝试:
def link_to_if_do condition, options = {}, html_options = {}
blockresult = yield
link_to_if condition, blockresult, options, html_options
end
You could always write your own conditional link helper, and put it in application_helper: 您总是可以编写自己的条件链接帮助器,并将其放在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
This is largely taken from link_to_unless , but modified to pass the block to link_to. 这很大程度上取自link_to_unless ,但已进行了修改以将块传递给link_to。 I've not tested this, but it should be enough to give you an idea.
我没有测试过,但是足以给您一个想法。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.