Ruby-on-rails 苗条的动态条件类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15242170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
slim dynamic conditional class
提问by Sergey Alekseev
Just to help other developers, because there is no similar question on SO.
只是为了帮助其他开发人员,因为在 SO 上没有类似的问题。
div class=(is_active? ? 'active' : 'inactive')
div class=('active' if is_active?)
回答by Sergey Alekseev
See the examples below:
请参阅以下示例:
div class=(is_active? ? 'active' : 'inactive')
div class=('active' if is_active?)
The same approach can be used to assign dynamic values to other attributes.
可以使用相同的方法将动态值分配给其他属性。
回答by Oleg Kr
I use array of classes and nil element if there is no need to include class in list, then compact array to remove nil elements and finally join all together.
如果不需要在列表中包含类,我使用类数组和 nil 元素,然后压缩数组以删除 nil 元素,最后将所有元素连接在一起。
div class=(["cday", "col-md-1", day.day == 1 ? "col-md-offset-#{day.cwday-1}" : nil].compact.join(' '))
回答by Maxim Zubarev
If you have multiple conditions I am doing right now something like
如果您有多个条件,我现在正在做的事情是
div class=(('foo ' if is_foo?) + ('bar' if is_bar?))
Though I feel it to be a blemish if is_bar? return false and the generated HTML results in
虽然我觉得如果 is_bar 是一个瑕疵?返回 false 和生成的 HTML 结果
<div class="foo "></div>
(the blemish is the blank character after the foo). If someone had a solution for that would be awesome.
(瑕疵是 之后的空白字符foo)。如果有人有解决方案,那就太棒了。

