代码之家  ›  专栏  ›  技术社区  ›  Simon Perepelitsa

如果Haml中的条件为真,则追加类

  •  144
  • Simon Perepelitsa  · 技术社区  · 15 年前

    如果 post.published?

    .post
      / Post stuff
    

    否则

    .post.gray
      / Post stuff
    

    我用rails助手实现了这一点,它看起来很难看。

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

    第二种变体:

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

    升级。Haml特定,但仍不简单:

    %div{:class => "post" + (" gray" unless post.published?).to_s}
      / Post stuff
    
    5 回复  |  直到 10 年前
        1
  •  334
  •   Nathan Weizenbaum    15 年前
    .post{:class => ("gray" unless post.published?)}
    
        2
  •  21
  •   yfeldblum    11 年前
    - 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
    
        3
  •  15
  •   mark    15 年前

    其实最好的办法就是把它放到助手里。

    %div{ :class => published_class(post) }
    
    #some_helper.rb
    
    def published_class(post)
      "post #{post.published? ? '' : 'gray'}"
    end
    
        4
  •  14
  •   Jared    11 年前

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

    其工作方式是对条件进行求值,如果为true,则字符串将包含在类中,如果不是,则不会包含。

        5
  •  5
  •   Drew Haines    7 年前

    更新的Ruby语法:

    .post{class: ("gray" unless post.published?)}
    
    推荐文章