Haml에서 조건이 참인 경우 클래스 추가


155

만약 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

답변:


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

73
여러 조건에 대한 참고 사항`{class : [(condition1)이 아닌 경우 '(class1'), (condition2)이면 'class2')]}`.. etc
— Mohammad AbuShady

5
여러 조건에 대한 간결한 내용 :{ class:[ (:class1 if cond1), (:class2 if cond2) ] }
— Phrogz

1
참고 : 괄호가 필요하거나 루비 구문 오류가 발생합니다.
— Topher Fangio

21
- 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

1
간결하지는 않지만 도우미에 넣으면 다른 방법보다 낫습니다.
— Simon Perepelitsa

3
이것은 잘 작동합니다- .compact.join(" ")그래도 필요하지 않은 것으로 나타났습니다 . 당신은 간단하게 할 수 있습니다:class => ["post active", ("gray" unless post.published?)]
— Stenerson

15

실제로 가장 좋은 방법은 도우미에 넣는 것입니다.

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

#some_helper.rb

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

이 파일을 도우미 파일에 넣었지만 "포스트"변수가 없다고 앱에서 알려줍니다.
— Simon Perepelitsa

2
참고 : 특정 경우에만 클래스를 포함하고 다른 경우에는 아무 것도 포함하지 않으려는 경우 nil설정 대신 속성을 설정할 수 없습니다.class=""
— MMachinegun

14

HAML에는이를 처리 할 수있는 좋은 방법이 있습니다.

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

이것이 작동하는 방법은 조건이 평가되고 참이면 문자열이 포함되지 않으면 클래스에 문자열이 포함되는 것입니다.


당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.