最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get automatically meta description and keywords in Rails? - Stack Overflow

programmeradmin1浏览0评论

I am developing an application with Rails 3, one of requeriments is unique meta descriptions and keywords on each page to improve the SEO.

The client needs that this do automatically. How do you do this? Is better do this with Rails, Ruby or directly with Javascript?

Thanks.

I am developing an application with Rails 3, one of requeriments is unique meta descriptions and keywords on each page to improve the SEO.

The client needs that this do automatically. How do you do this? Is better do this with Rails, Ruby or directly with Javascript?

Thanks.

Share Improve this question asked Jun 1, 2011 at 15:40 jrdijrdi 7151 gold badge10 silver badges26 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Do it in Rails, not via javascript. Search Engines will not execute your javascript.

What I usually do is write a meta helper that I simply stick in my ApplicationHelper, that looks like this:

def meta(field = nil, list = [])
  field = field.to_s
  @meta ||= {
    'robots' => ['all'],
    'copyright' => ['My Copyright'],
    'content-language' => ['en'],
    'title' => [],
    'keywords' => []
  }

  if field.present?
    @meta[field] ||= []
    case list.class
      when Array then
        @meta[field] += list
      when String then
        @meta[field] += [list]
      else
        @meta[field] += [list]
    end

    case field
      when 'description' then
        content = truncate(strip_tags(h(@meta[field].join(', '))), :length => 255)
      else
        content = @meta[field].join(', ')
    end

    return raw(%(<meta #{att}="#{h(field)}" content="#{h(content)}"/>))
  else
    tags = ''
    @meta.each do |field, list|
      tags += meta(field)+"\n"
    end
    return tags.rstrip
  end
end

You can simply set meta tags in your views, by adding a call to meta() in it. So in an articles/show.html.erb you might add this to the top of your view:

<% meta(:title, @article.title) %>

And in your layouts, you add it without any parameters, so it'll spit out the meta tags.

<%= meta %>

Or have it output an individual tag:

<%= meta(:title) %>

I bet you there's more elegant solutions, though. But if you were looking for something already implemented in Rails you're out of luck.

There are a number of Gems that address this issue. Take a look at:

  • meta-tags
  • seo_meta
发布评论

评论列表(0)

  1. 暂无评论