0

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

  • One way to do it is define an instance variable in your controller. For example, in your articles controller, before you render the view, `@page = 'Articles'`. Then in the view you can use `@page`. It's not clear to me, though, exactly what you mean when you say the name is "dynamic". – lurker Jun 01 '20 at 11:07
  • Possible duplicate of https://stackoverflow.com/questions/3757491/can-i-get-the-name-of-the-current-controller-in-the-view – spickermann Jun 01 '20 at 11:46

2 Answers2

2

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

Yakov
  • 3,033
  • 1
  • 11
  • 22
  • Thanks for getting back Yakov. So basically there's a small title in my _nav.html.erb file and it is hardcoded at Home. So when I go to all the pages it still says home. Whereas I would like this small title to change to the page I'm currently on. Be a bit more dynamic! I feel like it should be one line of code. I don't want to have to change the title in every view! That may be the only way to do it but I'm not sure! Thanks – James Clark Jun 01 '20 at 14:32
  • There is a link under you question provided by @spickermann. The solution based on a controller name. – Yakov Jun 01 '20 at 14:44
  • A title in `_nav.html.erb` could be added using breadcrumbs https://www.ruby-toolbox.com/categories/Breadcrumb_Builders – Yakov Jun 01 '20 at 14:47
  • Could make this a bit cleaner by just using `content_for(:title, 'Articles')` rather than the block syntax – engineersmnky Jun 01 '20 at 15:11
0

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.