Chapter 2

Tag Helpers

Set Open Graph tags in views and controllers

OpenGraph+ gives you helpers to set Open Graph meta tags from your views and controllers. These tags control how your pages appear when shared on social media.

Layout

First, add the open_graph_meta_tags helper to your layout’s <head>:

<html>
  <head>
    <%= open_graph_meta_tags %>
  </head>
</html>

This renders all the Open Graph meta tags you set throughout your request.

Views

Set tags directly in your view templates:

<% open_graph do |og|
  og.title = "My Page Title"
  og.description = "My Page Description"
end %>

Controllers

Set tags in a controller when you need to set them earlier, or across multiple actions:

before_action :set_open_graph_tags

private

def set_open_graph_tags
  open_graph do |og|
    og.title = "My Page Title"
    og.description = "My Page Description"
  end
end

Available tags

You can set any standard Open Graph tag:

<% open_graph do |og|
  og.title = "Page Title"
  og.description = "Page description"
  og.type = "article"
  og.url = request.original_url
  og.site_name = "My Site"
end %>

Dynamic tags

Use your model data to generate tags:

<% open_graph do |og|
  og.title = @post.title
  og.description = @post.excerpt
end %>

Or in a controller:

def show
  @post = Post.find(params[:id])

  open_graph do |og|
    og.title = @post.title
    og.description = @post.excerpt
  end
end