在我构建的每个webapp中,我都遇到了这个问题。我想有条件地在HTML元素上设置类。例如,有时
<div>
对于一个帖子来说:
<div class="post">...</div>
有时看起来像这样:
<div class="post even recent replied_to author_is_admin">...</div>
每节课之后
post
是因为某种逻辑决定了它应该存在吗?最好的方法是什么?在Rails+Haml,我做过如下的事情:
-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(' ')}
...
它不漂亮,我把它缩短为使用助手,这样我可以做到:
.post{:class => "#{cycle('even', 'odd')} #{post_classes}"}
它仍然看起来应该更容易阅读,因为它是我们一直在做的事情。你有什么方法可以使这个过程简短易读吗?