开发者

Conditional tags with HAML

I have this ham开发者_开发技巧l:

.kudobox
  %div.kudos= number_to_human_size_not_bytes kudos
  %div= (kudos == 1 || kudos == -1) ? "kudo" : "kudos"

Now I want the .kudobox have a positive, negative or zero class, depending on the number of kudos:

-# < 0 kudos
<div class="kudobox negative">

-# == 0 kudos
<div class="kudobox zero">

-# > 0 kudos
<div class="kudobox positive">

How can I achieve this? Thanks.


I know I can

%div{ :class => ( kudos < 0 ? "kudobox negative" : ( kudos == 0 ? "kudobox zero" : ( kudos > 0 ? "kudobox positive" : "kudobox impossible" ) ) ) }

But isn't there a shorter way?


I haven't looked too closely at your code (it's kind of confusing to read) to tell you if there's a shorter way, but I can say that you'd be much better off writing a helper method than having all of that logic in the view. A helper method with a plain old if or case statement would get the job done more cleanly, and then length wouldn't really be a factor. That way, you could replace the long conditional statement in your view with something easy on the eyes, like

%div{ :class => kudobox(kudos) }


If you want just short code without a helper, here you are:

.kudobox(class="#{kudos<0?'negative':kudos==0?'zero':'positive'}")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜