Rails I18n Cheatsheet

A cheatsheet for Rails internationalization, locales, and translations.

Relative Translations

You can prefix translations with a . to use relative lookups.

For example, if we render a message in a controller action:

class MessagesController < ApplicationController
  def create
    redirect_to root_path, notice: t(".success")
  end
end

This will look for the translation in:

en:
  messages:
    create:
      success: true

HTML Translations

Rails supports HTML safe translations by specifying the _html suffix or using the html key.

en:
  hello_html: <b>hello!</b>
  title:
    html: <b>title!</b>
<div><%= t('hello_html') %></div>
<div><%= t('title.html') %></div>

Interpolation

Rails translations support interpolation by passing in a hash of keys and values. If used in HTML translations, the values will be sanitized.

en:
  welcome_html: "<b>Welcome %{username}!</b>"
<%= t('welcome_html', username: @current_user.username) %>

Form Placeholders

Rails forms can lookup locales under the helpers.placeholder key based upon the model and attribute name.

<%= form.text_field :name, placeholder: true %>
en:
  helpers:
    placeholder:
      user:
        name: "Your name"

Want to stay up-to-date with Ruby on Rails?

Join 86,796+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.