【发布时间】:2010-10-19 23:31:51
【问题描述】:
在我构建的每个 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}"}
看起来它应该更容易阅读,因为这是我们一直在做的事情。你有什么方法可以使这个过程简短易读吗?
【问题讨论】:
标签: html ruby-on-rails coding-style haml