Skip to content

Instantly share code, notes, and snippets.

@airblade
Last active September 16, 2022 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airblade/70ab47ed073d75aa7f14551fbab0486c to your computer and use it in GitHub Desktop.
Save airblade/70ab47ed073d75aa7f14551fbab0486c to your computer and use it in GitHub Desktop.
Simple page titles in Rails
<html>
<head>
<title><%= title %></title>
<!-- ... -->
</head>
<!-- ... -->
</html>
module ApplicationHelper
# Accessor for page title.
#
# Call with a string to set the title.
# Call with a hash to translate the title and set the title to the result.
#
# Call without arguments to return the title that was previously set or
# the default translation, falling back to `:site_name`.
def title(val_or_options = nil)
case val_or_options
when String
content_for :title, val_or_options
when Hash
content_for :title, t('.title', **val_or_options)
when nil
content_for(:title) ||
t("#{controller_path.tr '/', '.'}.#{action_name}.title", default: :site_name)
end
end
end
# config/locales/en.yml
en:
site_name: My Site
people:
index:
title: People
show:
title: "%{name}"
<%# app/views/people/show.html.erb %>
<% title name: @person.name %>
<!-- ... -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment