James Clark
James Clark

Reputation: 3

How do I show the name of a page I am on in a Rails application

I have a header as follows

Home

But I want the name of the current page to be dynamic. For example when I visit the articles page the title should say articles, and The locations pages should say locations.

I am new to Ruby and Rails so this is probably very easy but I don't know how. Thanks in advance!

James

Upvotes: 0

Views: 526

Answers (2)

Yakov
Yakov

Reputation: 3191

Inside app/views/layouts/application.html.erb replace <title>...</title> by

<title>
  <% if content_for?(:title) %>
    <%= yield :title %>
  <% end %>
</title>

You'll be able to change the title dynamically from any other view, for instance:

# app/views/articles/index.html.erb

<% content_for(:title) do %>
  Articles
<% end %>
# app/views/locations/index.html.erb

<% content_for(:title) do %>
  Locations
<% end %>

Let's assume that you have @article object with name field

# app/views/articles/show.html.erb

<% content_for(:title) do %>
  @article.name
<% end %>

UPD

As suggested by @engineersmnky you can pass the title as a parameter content_for(:title, 'Articles')

https://apidock.com/rails/ActionView/Helpers/CaptureHelper/content_for

Upvotes: 2

Anton Volianskyi
Anton Volianskyi

Reputation: 1

In Your project folder open app/views/layouts/application.html.erb. This file contains head tag of every page in standard namespace of Your application. Name of page is inside of title tag. You can change it dynamicly by using <%= %> tag.

Upvotes: 0

Related Questions