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.
link_to_if
uses the block for a different purpose compared to link_to
. 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. 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.
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:
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. I've not tested this, but it should be enough to give you an idea. :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.