【问题标题】:Haml: Append class if condition is true in HamlHaml:如果在 Haml 中条件为真,则附加类
【发布时间】:2011-03-28 01:59:24
【问题描述】:

如果post.published?

.post
  / Post stuff

否则

.post.gray
  / Post stuff

我已经用 rails helper 实现了这个,它看起来很丑。

= 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特有的方法?

UPD。特定于 Haml,但仍然不简单:

%div{:class => "post" + (" gray" unless post.published?).to_s}
  / Post stuff

【问题讨论】:

    标签: ruby haml


    【解决方案1】:

    更新 Ruby 语法:

    .post{class: ("gray" unless post.published?)}
    

    【讨论】:

      【解决方案2】:

      HAML 有一个很好的内置方法来处理这个问题:

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

      其工作方式是条件被评估,如果为真,则字符串被包含在类中,如果不是,则不会被包含。

      【讨论】:

        【解决方案3】:
        - 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
        

        【讨论】:

        • 不是那么简洁,但如果放入助手中看起来比其他方式更好。
        • 这很好用——我注意到你不需要.compact.join(" ")。你可以简单地做:class => ["post active", ("gray" unless post.published?)]
        【解决方案4】:

        最好的办法是把它放到一个助手中。

        %div{ :class => published_class(post) }
        
        #some_helper.rb
        
        def published_class(post)
          "post #{post.published? ? '' : 'gray'}"
        end
        

        【讨论】:

        • 我已将它放在我的帮助文件中,但我的应用程序告诉我,没有“post”变量。
        • fyi:如果您只想在特定情况下包含一个类,而在其他情况下不包含任何内容,您可以设置 nil 并且不会设置属性,而不是设置 class=""跨度>
        【解决方案5】:
        .post{:class => ("gray" unless post.published?)}
        

        【讨论】:

        • 只是多个条件的旁注` {class: [('class1' unless condition1), ('class2' if condition2)]} ` .. etc
        • 更简洁的多个条件:{ class:[ (:class1 if cond1), (:class2 if cond2) ] }
        • 注意:括号是必需的,否则会出现 ruby​​ 语法错误。
        • 更新了 json 样式的表示法:.post{class: ("gray" unless post.published?)}
        猜你喜欢
        • 1970-01-01
        • 2014-07-17
        • 2015-08-04
        • 2012-11-14
        • 2013-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多