Books

image by Annie Spratt

Set your page title in the view template using content_for

Rails uses content_for as its primary way to store content in one place for use in other views, layouts or helpers. Find out more about content_for in the Rails documentation in the ActionView helpers section.

RailsConf 2024

I'm co-chairing RailsConf 2024 in Detroit May 7–9. Come and join us 

Instead of…

…using an instance variable in the controller…

things_controller.rb

def show
  @page_title = 'Page Title'
  # other controller stuff
end

And views/layouts/application.html.erb

In the <head>.

<title><%= @page_title || 'Default' %></title>

Use…

content_for and yield.

things/show.html.erb

I like to put the title at the top of the individual view file.

<% content_for(:html_title) { 'Title' } %>

And views/layouts/application.html.erb

In the <head>.

<title><%= content_for?(:html_title) ? yield(:html_title) : "Default" %></title>

But why?

Using content_for keeps information about how to render the HTML inside the relevant view template, avoiding cluttering the controller with non-business logic.

You avoid creating yet another ‘magic’ instance variable that gets automatically passed to the view by Rails.

The content for the <title> is not referenced or referred to when rendering JSON or AJAX from the same controller action. Only the rendered HTML ever accesses that information. Therefore, there’s no need to expose this information in an instance variable: it belongs solely in the html.erb view template.

Why not?

You are ignoring the framework’s tools if you use the instance variable approach, but it does work.


Translated into Japanese here

Brighton Ruby 2024

Still running UK’s friendliest, Ruby event on Friday 28th June. Ice cream + Ruby 


Last updated on December 11th, 2017 by @andycroll

An email newsletter, with one Ruby/Rails technique delivered with a ‘why?’ and a ‘how?’ every two weeks. It’s deliberately brief, focussed & opinionated.