The following code set's up the minimal required meta tags for Social Media and Search Engines using the MetaTags gem. ([https://moz.com/blog/meta-data-templates-123])
You can easily extend this with other properties. Setting this up with a couple of helper functions makes it easy to extend and maintain.
Installation
Add the "meta-tags" gem to your Gemfile.
gem 'meta-tags'
And run bundle install
command.
MetaTags Usage
First, add this code to your main layout:
<head>
<%= display_meta_tags site: 'My website' %>
</head>
Then, to set the page title, add this to each of your views (see below for other options):
<h1><%= title 'My page title' %></h1>
When views are rendered, the page title will be included in the right spots:
<head>
<title>My website | My page title</title>
</head>
<body>
<h1>My page title</h1>
</body>
Setting up default values
Let's add a helper function to setup default values
def default_meta_tags
{
site: 'Site Name',
title: '',
reverse: true,
separator: '|',
description: 'Site Description',
keywords: 'your, key, words',
canonical: request.original_url,
noindex: !Rails.env.production?,
icon: [
{ href: image_url('logo.png') },
{ href: image_url('logo.png'), rel: 'apple-touch-icon', sizes: '180x180', type: 'image/png' },
],
og: {
site_name: 'Site Name',
title: '',
description: 'Site Description',
type: 'website',
url: request.original_url,
image: image_url('social.jpg')
}
}
end
Implement the helper function in your main layout
<head>
<%= display_meta_tags(default_meta_tags %>
</head>
Overriding the default values
The following example overrides the default values for a Post model. (Add this code to the show.erb for example)
set_meta_tags title: @post.title,
description: @post.intro,
twitter: {
card: "summary",
site: "@getSmart_NL"
},
og: {
title: @post.title,
description: @post.intro,
image: image_url(@post.header.attached? ? url_for(@post.header) : "social.jpg"),
type: "article"
}
*Instructions based on MetaTags readme and tweaked to my personal usage.
Top comments (0)