【发布时间】:2014-11-04 15:32:35
【问题描述】:
我有一个带有文件附件的Post,通过 Carrierwave。
在我看来,根据附件的类型,我希望显示不同的图标。
所以这就是我想出的,现在效果很好,但很不合时宜,而且不干。
如何简化它并使其更符合 Rails 风格?
<% if post.file? %>
<% if post.file.file.extension.downcase =~ /mp3|wav/ %>
<i class="fa fa-file-audio-o"></i>
<% elsif post.file.file.extension.downcase =~ /pdf/ %>
<i class="fa fa-file-pdf-o"></i>
<% elsif post.file.file.extension.downcase =~ /txt/ %>
<i class="fa fa-file-text-o"></i>
<% elsif post.file.file.extension.downcase =~ /doc|docx/ %>
<i class="fa fa-file-word-o"></i>
<% elsif post.file.file.extension.downcase =~ /xls|xlsx/ %>
<i class="fa fa-file-excel-o"></i>
<% elsif post.file.file.extension.downcase =~ /ppt|pptx/ %>
<i class="fa fa-file-powerpoint-o"></i>
<% elsif post.file.file.extension.downcase =~ /mp4|m4v|mov|avi|mkv/ %>
<i class="fa fa-file-video-o"></i>
<% end %>
<% end %>
编辑 1
我还希望能够轻松检测扩展名是什么类型的文件,然后对其进行一些行为。这个图标版本只是一个应用程序。
另一个例子是我的分享按钮。根据附加文件的类型,我想添加共享标题中包含的文件的名称。比如:
如果没有这个逻辑,我的 Twitter 分享图标看起来像这样:
<a class="btn btn-twitter" href='http://twitter.com/home?status=<%=u "#{post.title} - Read more at #{post_url(post)}" %>' title="Share on Twitter" target="_blank">
<i class="fa fa-twitter"></i>
</a>
用逻辑:
<% if post.file? %>
<a class="btn btn-twitter" href='http://twitter.com/home?status=<%=u "#{post.title} (#{post.file.file.extension.upcase} Included) - Read more at #{post_url(post)}" %>' title="Share on Twitter" target="_blank">
<i class="fa fa-twitter"></i>
</a>
<% end %>
有没有更优雅的 Railsy 方法来解决这个问题?
编辑 2
有了@blelump 的美妙、优雅的解决方案——我喜欢它——我正在尝试这个:
<i class='fa attached-<%= post.file.file.extension.downcase %>'></i>
在我的post.css.scss 中,我有这些规则:
.attached-mp3, .attached-wav {
@extend .fa-file-audio-o;
}
.attached-pdf {
@extend .fa-file-pdf-o;
}
.attached-txt {
@extend .fa-file-text-o;
}
问题是,由此产生的 HTML 是这样的:
<i class="fa attached-txt"></i>
它似乎没有调用@extend .fa-file-text-o。
我该如何解决这个问题?
编辑 3
这就是我的post.css.scss 处理@blelump 建议的方式:
.field_report{
width: 100%;
}
.field_report #report_box{
width: 100%;
height: 250px;
}
.attached-mp3, .attached-wav {
@extend .fa-file-audio-o;
}
.attached-pdf {
@extend .fa-file-pdf-o;
}
.attached-txt {
@extend .fa-file-text-o;
}
.attached-doc, .attached-docx {
@extend .fa-file-word-o;
}
.attached-xls, .attached-xlsx {
@extend .fa-file-excel-o;
}
.attached-ppt, .attached-pptx {
@extend .fa-file-powerpoint-o;
}
.attached-mp4, .attached-m4v, .attached-mov, .attached-mkv, .attached-avi {
@extend .fa-file-video-o;
}
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 dry view-helpers