简体   繁体   中英

Controller Dependant Title in Application Layout File - Ruby on Rails

I am asking a question to see if how I implemented something could be improved or to see if there is a standard to solving problems like it. I am fairly new to the rails framework and want some clarification.

Inside my application.html.erb layout I have added a title bar at the top of the page. When I navigate pages I want the text in the title bar to change to pages name. Now the reason I wanted to added the title bar into the application layout is because everything can be shared so it seems silly to put it in controller views if all that needs to change is the title. Below is the excerpt from application.html.erb:

<h2 class="header-title"><%= $title %></h2>

And what I have done to solve the problem is I've created a global variable $title that I change in my different controllers. Like below:

class JobsController < ApplicationController
   $title = "Jobs"

class PagesController < ApplicationController
   $title = "Dashboard"

I feel like creating a global variable is silly, can this be done differently?

Thanks in advance for any insight.

Considering the title is very much a view-specific responsibility, I would be inclined to keep it in the views. You can do this by yielding a block that you later define the content_for in your template files.

application.html.erb

<h2 class="header-title"><%= yield(:title) %></h2>

myaction.html.erb

<% content_for(:title) { 'My Custom Title' } %>

Or, as per comments - content_for :title, 'My Custom Title'

The other option I like is using an application helper to manage the behaviour.

application_helper.rb

def title
  yield(:title) || 'My Default Title'
end

application.html.erb

<h2 class="header-title"><%= title %></h2>

Better yet, use internationalisation and store all your titles in there.

I don't think it's necessary to use a global variable. A simple

@title = 'Jobs'

and

<h2 class="header-title"><%= @title %></h2>

should be enough.

ApplicationController.rb

class ApplicationController < ActionController::Base

  before_filter do
    @title = request.controller_class.to_s
  end

end

layout

<h2 class="header-title"><%= @title %></h2>

You could create a helper function for each controller like so:

In app/helpers/my_helper.rb :

def title
  "Title for controller"
end

In app/views/layouts/application.html.erb :

<h2 class="header-title"><%= title %></h2>

The application layout will automatically choose the correct title helper for you.

Try this,

<title><%= @title || controller_name.capitalize %></title>

How does this work?

  • Defaults to controller name
  • Uses @title if an action sets a custom title

This is taken from one of our production apps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM