Ruby on Rails实战之二:网站搜索引擎优化上篇
SEO对网站推广的作用是至关重要的。Ruby on rails作为现代的专为web量身定制的框架,处理SEO相当便利。今天,我来分享一下在实际的ROR网站运营中的SEO的一些Tips。
1.页面基本元素SEO
页面基本元素设置是做页面级SEO中最基本,最简单,同时也是最重要的处理。页面基本元素的设置,简单的说就是 页面title,description,keywords的设置。
这些元素的的内容可以采用简单的方法直接设置,通常在controller的action里设置变量@title,然后在view中引用,例如下面的代码:
# 在 controoler action 中的代码
...
@title = "这是页面标题"
...
#在view中的代码
...
<title><%= @title %></title>
...
上面的方法简单明了。但是title等页面数据本属于view层的内容,放在action中设置并不直观,也不易修改,我使用的是另外一种方法,代码如下:
# 在 ApplicationHelper 中定义方法
#set the title for the page
def title(page_title)
content_for(:title) do
"#{page_title} - xx网"
end
end
#set the description for the page
def description(page_description)
content_for(:description) do
"<meta name=\"description\" content=\"#{page_description}\" />\n"
end
end
#set the keywords for the page
def keywords(page_keywords)
content_for(:keywords) do
"<meta name=\"keywords\" content=\"#{page_keywords}\" />\n"
end
end
#layout application 的代码
...
<title><%= yield(:title) || 'xx网'%></title>
<%= yield(:description)%><%= yield(:keywords)%>
...
# 具体页面view的代码
<% title "这个是页面title" -%>
<% description "这个是页面描述" -%>
<% keywords "ror页面seo" -%>
....
这样,每个页面的title等元素都是在自己页面view中,便于设置和修改。
2.去除干扰信息
SEO中一个重要的概念就是内容和主题(关键字)越契合,排名就可能越靠前。但是在页面显示内容是常常会显示一些不相关的内容,例如边栏工具条,广告内容等。
这个时候常常把这些内容写成javascript document.write输出,搜索引擎会忽略javascript中的内容,从而达到去除干扰信息的目的。
ror可以把这个方法很好的包装,以更方便的使用,看代码:
#在 ApplicationHelper中定义如下方法
#html to javascript
def document_write(options={},&block)
pos = output_buffer.length
block.call
str = output_buffer[pos..-1]
output_str = "<script type=\"text/javascript\">\ntry {\n"
str.each_line do |s|
output_str << "document.write(\"#{s.rstrip}\");\n"
end
output_str << " } catch(err) { } \n </script>\n"
output_buffer.replace("#{output_buffer[0..pos]}\n#{output_str}")
end
这个时候,view中希望以document.write输出的内容写成
...
<% document_write do %>
it is very good.
haha<%=Time.now%>
<%="very good"%>
这里面的文章将通过javascript输出
<input type='text' name='yes' value='hello'/>
<% end %>
...
实际输出html如下
<script type="text/javascript">
try {
document.write("");
document.write(" it is very good.");
document.write(" hahaFri May 29 00:20:06 +0800 2009");
document.write(" very good");
document.write(" 这里面的文章将通过javascript输出");
document.write(" <input type='text' name='yes' value='hello'/>");
} catch(err) { }
</script>
下篇讲一下如何做相关推荐,以及如何编织站内链接网,待续。
output_buffer这个方法没有定义怎么办?
title的那个问题有简单的办法的,就像liuqiang说的那样,可以参见这里
http://guides.rubyonrails.org/layouts_and_rendering.html#understanding-yield
def document_write(options={},&block)
pos = output_buffer.length
block.call
str = output_buffer
如果用 def document_write(options={},&block)
#pos = output_buffer.length
str = block.call
#str = output_buffer
去掉注消的部分会有问题么?
应该是在具体的视图页面中加
BTW:没注意,这是篇同步到论坛的博客 :o
很不错。 :D
这个网站有很多有用的rails方面的seo技巧。 http://www.seoonrails.com/ http://www.bingocardcreator.com/articles/rails-seo-tips.htm 虽然时间有些早,但很实用。