我有一個Post
,它通過Carrierwave具有文件附件。如何以關注或助手或其他方式烘乾此視圖?
在我看來,根據附件的類型,我想要顯示不同的圖標。
所以這就是我想到的,現在工作正常,但很不合適,而不是幹。
如何簡化這個並使其更加Rails-y?
<% 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
這是後@ blelump的建議我post.css.scss
的樣子:
.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;
}
所以我只想在我的'.scss創建所有擴展這些規則else語句聲明它'文件?你介意爲我的所有規則編輯這個,所以我可以確切地知道我的SASS文件會是什麼樣子?日Thnx! – marcamillion 2014-11-04 15:42:44
是的,當然還有其他解決方案,包括向你的幫手中添加一些邏輯,但這裏沒有必要。這是肯定的最快的。 – blelump 2014-11-04 15:45:33
這是一個不錯的優雅解決方案。我遇到的問題是我想做一些更復雜的事情。我剛剛更新了我的問題。你能否讚揚你的答案也包括一個方法呢?謝謝! – marcamillion 2014-11-04 15:59:30