Append class if condition is true in Haml

后端 未结 5 1455
温柔的废话
温柔的废话 2020-11-30 17:50

If post.published?

.post
  / Post stuff

Otherwise

.post.gray
  / Post stuff

I\'ve implemente

相关标签:
5条回答
  • 2020-11-30 18:29
    - 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
    
    0 讨论(0)
  • 2020-11-30 18:31

    Really the best thing is to put it into a helper.

    %div{ :class => published_class(post) }
    
    #some_helper.rb
    
    def published_class(post)
      "post #{post.published? ? '' : 'gray'}"
    end
    
    0 讨论(0)
  • 2020-11-30 18:39

    HAML has a nice built in way to handle this:

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

    The way that this works is that the conditional gets evaluated and if true, the string gets included in the classes, if not it won't be included.

    0 讨论(0)
  • 2020-11-30 18:50
    .post{:class => ("gray" unless post.published?)}
    
    0 讨论(0)
  • 2020-11-30 18:53

    Updated Ruby syntax:

    .post{class: ("gray" unless post.published?)}
    
    0 讨论(0)
提交回复
热议问题