Añadir clase si la condición es verdadera en Haml


Si post.published?

.post
  / Post stuff

De lo contrario

.post.gray
  / Post stuff

He implementado esto con rails helper y parece feo.

= content_tag :div, :class => "post" + (" gray" unless post.published?).to_s do
  / Post stuff

Segunda variante:

= content_tag :div, :class => "post" + (post.published? ? "" : " gray") do
  / Post stuff

¿Hay una manera más simple y específica de haml?

UPD. Haml-específico, pero todavía no simple:

%div{:class => "post" + (" gray" unless post.published?).to_s}
  / Post stuff
 139
Author: Nakilon, 2010-08-11

5 answers

.post{:class => ("gray" unless post.published?)}
 298
Author: Nathan Weizenbaum,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-11 00:50:57
- classes = ["post", ("gray" unless post.published?)]
= content_tag :div, class: classes do
  /Post stuff

def post_tag post, &block
  classes = ["post", ("gray" unless post.published?)]
  content_tag :div, class: classes, &block
end

= post_tag post
  /Post stuff
 21
Author: yfeldblum,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-01 05:09:45

Realmente lo mejor es ponerlo en un ayudante.

%div{ :class => published_class(post) }

#some_helper.rb

def published_class(post)
  "post #{post.published? ? '' : 'gray'}"
end
 13
Author: mark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-11 05:37:03

HAML tiene una buena forma de manejar esto:

.post{class: [!post.published? && "gray"] }

La forma en que esto funciona es que el condicional se evalúa y si es verdadero, la cadena se incluye en las clases, si no, no se incluirá.

 12
Author: Jared,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-10 17:40:21

Sintaxis actualizada de Ruby:

.post{class: ("gray" unless post.published?)}
 0
Author: Drew Haines,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-14 05:35:41