Skip to content

Instantly share code, notes, and snippets.

@nicolasblanco
Created July 7, 2011 12:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nicolasblanco/1069378 to your computer and use it in GitHub Desktop.
Save nicolasblanco/1069378 to your computer and use it in GitHub Desktop.
Rails i18n framework for your meta tags

Rails i18n framework for your meta tags

Here is a convenient method for page titles and other meta tags.

One common solution is to use "yield" and some kind of helpers that would call content_for (like in this Railscasts).

The problem is that for Search Engines Optimization, you should change all your meta tags for every page to avoid duplicate content, and call your helpers on every page...

This workaround uses the i18n framework and tries to find the good tags depending on the page you are, so you don't have to call any helper by default.

  / application.html.haml
  
  %head
    %title= t_meta(:title)

    %meta{ :name => "description", :content => t_meta(:description) }
    %meta{ :name => "keywords", :content => t_meta(:keywords) }
  module ApplicationHelper

    def t_meta_interpolation(name, hash)
      instance_variable_set("@#{name}_interpolation", hash)
    end

    def t_meta(name)
      interpolation_data = instance_variable_get("@#{name}_interpolation") || {}
      t("meta.#{controller_path.gsub("/", ".")}.#{action_name}.#{name}",
        interpolation_data.merge({ :default => t("meta.defaults.#{name}") }))
    end
  # ...
  end
  en:
    meta:
      defaults:
        title: "OMFG! Awesome Site!"
        description: "This site is full of win, really!"
        keywords: "awesomeness, win, great, pipo, hey"

      products:
        index:
          title: "OMFG! Awesome products here!"
          description: "Find here my great products!"
         keywords: "products, win, great, super, pipo, hai"

Advanced use with interpolation

You can use the helper t_meta_interpolation to use interpolation in your meta tags. ie. : you want to display the name and category of your product on your product page.

  / show.html.haml
  - t_meta_interpolation :title, :name => @product.name, :category => @product.category

  %h1= @product.name
  
  /...
  en:
    meta:
      products:
        show:
          title: "My great site - My great product %{category} - %{name}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment