posted on Tuesday, June 01, 2010
Here is some ways to manage html titles, keywords and description to have a seo friendly website:
Lazy way is to use an instance variable, which has a default value and you could override it in any controller's action:
controllers/posts.rb :
def index
@title = "Index title"
end
views/posts/index.html.erb :
<%=@title ||= "Default title"%>
If there is not too many pages on the website its better to use a helper with all titles and descriptions you need, to keep controllers clean from that kind of stuff. Also this method works good for those who want to have all their titles, descriptions etc. in one place to track it very easily.
helpers/application_helper.rb :
def title
titles = {
:blog => {
:index => "Index title",
:default => "Any other action title"
},
:users => {
:index => "Index title",
:show => "Show title",
:default => "Any other action title"
},
:default => "Default title"
}
c = params[:controller].to_sym
a = params[:action].to_sym
return titles[c] ? titles[c][a] ? titles[c][a] : titles[c][:default] : titles[:default]
end
views/layouts/application.html.erb :
<%=@title || title%>
Another one is content_for method, which probably is the best for 90% of websites:
views/layouts/application.html.erb :
<%= yield(:title) || "Default title" %>
views/posts/index.html.erb :
<%= title "Page title" %>
helpers/application_helper.rb :
def title html_title
content_for :title do
html_title
end
end
It's a good idea to move titles, description and keywords out from controllers because it is entirely a view responsibility even if you need them to be dynamicly made with user names or post tags.
Continue reading