programing

Haml: Haml에서 조건이 참이면 클래스를 추가합니다.

minimums 2023. 6. 22. 21:39
반응형

Haml: Haml에서 조건이 참이면 클래스를 추가합니다.

한다면post.published?

.post
  / Post stuff

그렇지않으면

.post.gray
  / Post stuff

레일 도우미와 함께 구현했는데 보기 흉합니다.

= 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

더 간단하고 햄에 특화된 방법이 있습니까?

UPD. 햄에 특화되었지만 여전히 간단하지 않습니다.

%div{:class => "post" + (" gray" unless post.published?).to_s}
  / Post stuff
.post{:class => ("gray" unless post.published?)}
- 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

정말로 가장 좋은 것은 그것을 도우미에게 맡기는 것입니다.

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

#some_helper.rb

def published_class(post)
  "post #{post.published? ? '' : 'gray'}"
end

HAML은 이를 처리할 수 있는 좋은 기능을 제공합니다.

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

이 방법은 조건부를 평가하고 참인 경우 문자열이 클래스에 포함되지만 그렇지 않은 경우 포함되지 않습니다.

업데이트된 Ruby 구문:

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

언급URL : https://stackoverflow.com/questions/3453560/haml-append-class-if-condition-is-true-in-haml

반응형