在Rails 5中为每个显示页面添加数据库中的不同元标记

问题描述 投票:0回答:1

我在数据库中有事件记录,每个记录都有一个“meta_keywords”字段。

当我显示一个事件时,我想在页面中生成元标记,以便搜索引擎可以引用事件显示页面。

预期:

<meta name="description" content="My great event">
<meta name="keywords" content="Event topics">

我怎么能在rails 5中做到这一点?

ruby-on-rails ruby-on-rails-5
1个回答
0
投票

在这里找到答案的详细步骤:https://nithinbekal.com/posts/rails-page-titles/

module ApplicationHelper
  def meta_tag(tag, text)
    content_for :"meta_#{tag}", text
  end

  def yield_meta_tag(tag, default_text='')
    content_for?(:"meta_#{tag}") ? content_for(:"meta_#{tag}") : default_text
  end
end

在layouts / application.html.erb的head部分中:

<meta name='description'
  content='<%= yield_meta_tag(:description, 'Default description') %>' />
<meta name='keywords'
  content='<%= yield_meta_tag(:keywords, 'defaults,ruby,rails') %>' />

在帖子#show中:

<% meta_tag :description, @post.description %>
<% meta_tag :keywords, @post.keywords.join(',') %>
© www.soinside.com 2019 - 2024. All rights reserved.