2

In every webapp I build, I come across this issue. I want to set classes on HTML elements conditionally. For example, sometimes the <div> for a post looks like:

<div class="post">...</div>

And sometimes it looks like this:

<div class="post even recent replied_to author_is_admin">...</div>

Each class after post is there because some logic decided it should be. What is the best way to this? In Rails+HAML, I've been guilty of doing stuff like:

-classes = []
-classes << cycle('even', 'odd')
-classes << 'recent' if post.recent?
-classes << 'replied_to' if post.replied_to?
-classes << 'author_is_admin' if post.author_is_admin?
.post{:class => classes.join(' ')}
    ...

It's not pretty, and I've shortened it to use a helper so I can do this:

.post{:class => "#{cycle('even', 'odd')} #{post_classes}"}

It still seems like it should be easier to read, because it's something we do all the time. Does you have any methods by which you make this process short and readable?

4

1 回答 1

1

我认为你所做的很好。我只会建议一些小的改进。一种是将循环调用放在 post_classes 中。为了可读性,我会让 post_classes 接受 Post 参数。这会产生一些冗余,但您可以通过定义此辅助方法轻松避免它:

def classes(object)
  case object
  when Post then post_classes(object)
  end
end

这样,您的模板代码将如下所示:

.post{:class => classes(Post)}
于 2009-04-16T22:21:56.173 回答