concatenate link_to with pipe

痞子三分冷 提交于 2020-01-07 05:37:04

问题


I want to concatenate a few links with a pipe. But all links are surrounded by an if-statement.

Example:

- if condition1
  = link_to link1

- if condition2
  = link_to link2

- if condition3
  = link_to link3

If condition 1 and 2 are true, the result should be

link1 | link2

Any hints how to do this?


回答1:


I would use smth like that for that purpose:

= [[l1, c1], [l2, c2], [l3, c3]].map{ |l, c| link_to(l) if c }.compact.join('|')

or

= [(link_to(l1) if c1),(link_to(l2) if c2),(link_to(l3) if c3)].compact.join('|')

The last one is a bit clumsy but it's a matter of taste. Both works perfectly for filtering out unnecessary links and joining the rest of them with |.

Though, if your conditions are non-trivial and you have quite a few of them it'd be better to move that logic outside of view into controller or some helper (depending on the situation).

And if you have some common method for testing whether you should display link or not, let's say show?(link) helper, then things become a bit nicer and you can do it like that:

= [l1, l2, l3, l4].map{ |l| link_to(l) if show?(l) }.compact.join('|')

or like that:

= [l1, l2, l3, l4].select{ |l| show?(l) }.map{ |l| link_to(l) }.join('|')


来源:https://stackoverflow.com/questions/8639847/concatenate-link-to-with-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!