admin管理员组

文章数量:1386692

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

本文标签: javascriptHow to get automatically meta description and keywords in RailsStack Overflow