用管道连接 link_to [英] concatenate link_to with pipe

查看:40
本文介绍了用管道连接 link_to的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用管道连接几个链接.但是所有链接都被一个 if 语句包围.

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

示例:

- if condition1
  = link_to link1

- if condition2
  = link_to link2

- if condition3
  = link_to link3

如果条件 1 和 2 为真,结果应该是

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

link1 | link2

任何提示如何做到这一点?

Any hints how to do this?

推荐答案

为了这个目的,我会像这样使用 smth:

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('|')

= [(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).

如果你有一些通用的方法来测试你是否应该显示链接,比如 show?(link) 助手,那么事情会变得更好,你可以这样做:

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('|')

或者像这样:

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

这篇关于用管道连接 link_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆