超细动态条件类

只是为了帮助其他开发人员,因为在 SO 上没有类似的问题。

div class=(is_active? ? 'active' : 'inactive')
div class=('active' if is_active?)
47761 次浏览

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.

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

<div class="foo "></div>

(the blemish is the blank character after the foo). If someone had a solution for that would be awesome.

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.

div class=(["cday", "col-md-1", day.day == 1 ? "col-md-offset-#{day.cwday-1}" : nil].compact.join(' '))