Last active
September 16, 2022 10:41
-
-
Save airblade/70ab47ed073d75aa7f14551fbab0486c to your computer and use it in GitHub Desktop.
Simple page titles in Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title><%= title %></title> | |
<!-- ... --> | |
</head> | |
<!-- ... --> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/locales/en.yml | |
en: | |
site_name: My Site | |
people: | |
index: | |
title: People | |
show: | |
title: "%{name}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%# 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