接續上一篇 [RoR] 簡單加入 Tag, Tagging 標籤功能 ,還需要把所有的標籤列出來,並且可以用 Tag Cloud 的方式呈獻,就是像 IT邦幫忙的熱門標籤的樣子:
標籤雲的實作
有關 Tag Cloud 怎麼從 Tag 的多寡來算出 Tag 的字型大小的原理,有 Tag Cloud Font Distribution Algorithm 這一篇文章探討其演算法,若希望能夠有現成的程式碼來應用的話,幸好,在 Tagging & Tag Clouds Made Easy 這一文中,提供很簡單的方式就可以把標籤雲實作出來:
首先在 app/helpers/application_helper.rb 加入:
module ApplicationHelper
def tag_cloud( tags )
classes = %w(cloud1 cloud2 cloud3 cloud4 cloud5 cloud6 cloud7)
max, min = 0, 0
tags.each { |t|
max = t[1].to_i if t[1].to_i > max
min = t[1].to_i if t[1].to_i < min
}
divisor = ((max - min) / classes.size) + 1
tags.each { |t|
yield t[0], classes[(t[1].to_i - min) / divisor]
}
end
end
編輯 CSS 檔案 public/stylesheets/cloud.css
.cloud1 {font-size: 100%;}
.cloud2 {font-size: 120%;}
.cloud3 {font-size: 140%;}
.cloud4 {font-size: 160%;}
.cloud5 {font-size: 180%;}
.cloud6 {font-size: 200%;}
.cloud7 {font-size: 220%;}
# 然後記得在 app/views/layouts/blog.html.erb 加入
<%= stylesheet_link_tag 'cloud' %>
如果需要有更具特色的 Tag Cloud 的顯示,可參考 Tag Clouds Gallery: Examples And Good Practices 這篇文,裡面列出許多不同的 Tag Cloud 的設計。
編輯 app/views/blog/index.html.erb
<div id="cloud_area">
<% tag_cloud Article.tags_count do |name, css_class| -%>
<%= link_to name, tagged_articles_path(name), :class => css_class -%>
<% end -%>
</div>
再加上一些 CSS 語法,所呈獻的畫面為:
加入可切換 Tag Cloud, Tag List 的機制
模仿 del.icio.us 可以切換 標籤雲 或 標籤列表,將 index.html.erb 改為
<% if session['tagtype'] == 'cloud' -%>
<div id="cloud_area">
<h4>標籤 <%= link_to '表', '?tagtype=list' -%>|| 雲</h4>
<% tag_cloud Article.tags_count do |name, css_class| -%>
<%= link_to name, tagged_articles_path(name), :class => css_class -%>
<% end -%>
</div>
<% else -%>
<div id="list_area">
<h4>標籤 表 ||<%= link_to '雲', '?tagtype=cloud' -%></h4>
<% Article.tags_count.sort.each do |pair| -%>
<%= link_to(pair[0], tagged_articles_path(pair[0])) -%>(<%= pair[1] -%>)
<% end -%>
</div>
<% end -%>
就可以依 Sessions 中所設的 tagtype 的值,來決定以 Tag Cloud 或者 Tag List 的值來呈獻;而使用者也可以從頁面來選擇何種方式來瀏表 所有的標籤。
而在 app/controllers/blog_controller.rb 的 def index 之中加入:
if params[:tagtype] == 'list'
session['tagtype'] = 'list'
elsif params[:tagtype] == 'cloud'
session['tagtype'] = 'cloud'
else
session['tagtype'] = 'cloud'
end
就可以記住使用者選擇的呈獻模式,而讓 views 間接依據這邊的變化做改變。
像這種可以讓使用者做選擇如何呈獻的方式,可以用同樣的方式來建置,例如像:整個 template 主題的變換、顏色、字型大小的切換,甚至像每頁一次秀出幾筆資料的選擇等,讓使用者可以對網頁的呈獻方式有更多的選擇。