苗条的动态条件类

Ser*_*eev 97 ruby-on-rails slim-lang

只是为了帮助其他开发者,因为SO上没有类似的问题.

div class=(is_active? ? 'active' : 'inactive')
div class=('active' if is_active?)
Run Code Online (Sandbox Code Playgroud)

Ser*_*eev 135

请参阅以下示例:

div class=(is_active? ? 'active' : 'inactive')
div class=('active' if is_active?)
Run Code Online (Sandbox Code Playgroud)

可以使用相同的方法将动态值分配给其他属性.

  • 这也可以附加一个类,例如:`div.councilor class =(councilor.retired??"retired":"")`generate:`div.councilor.retired` (3认同)
  • 你会如何在多种条件下做到这一点? (2认同)

小智 19

如果不需要在列表中包含类,则使用类和nil元素的数组,然后使用紧凑数组删除nil元素并最终将所有元素连接在一起.

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


Max*_*rev 11

如果你有多种条件我现在正在做的事情

div class=(('foo ' if is_foo?) + ('bar' if is_bar?))
Run Code Online (Sandbox Code Playgroud)

虽然如果is_bar我觉得它是一个瑕疵?返回false并生成HTML结果

<div class="foo "></div>
Run Code Online (Sandbox Code Playgroud)

(瑕疵是后面的空白字符foo).如果有人有解决方案,那就太棒了.

  • 在这种情况下尝试`String#rstrip`有2个条件:`div class =((('foo'if is_foo?)+('bar'if is_bar?)).rstrip)`.或者`div class =([('foo'if is_foo?),('bar'if is_bar?)].compact.join(''))`用于几个条件. (7认同)