rails page titles

2019-01-21 08:25发布

问题:

I don't like the way rails does page titles by default (just uses the controller name), so I'm working on a new way of doing it like so:

application controller:

def page_title
    "Default Title Here"
end

posts controller:

def page_title
    "Awesome Posts"
end

application layout:

<title><%=controller.page_title%></title>

It works well because if I don't have a page_title method in whatever controller I'm currently using it falls back to the default in the application controller. But what if in my users controller I want it to return "Signup" for the "new" action, but fall back for any other action? Is there a way to do that?

Secondly, does anyone else have any other ways of doing page titles in rails?

回答1:

I disagree with the other answers, I believe the title shouldn't be set per action, but rather within the view itself. Keep the view logic within the view and the controller logic within the controller.

Inside your application_helper.rb add:

def title(page_title)
  content_for(:title) { page_title }
end

Then to insert it into your <title>:

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

So when you are in your views, you have access to all instance variables set from the controller and you can set it there. It keeps the clutter out of the controller as well.

<%- title "Reading #{@post.name}" %>


回答2:

I like to put a catchall, default title in my layout that can be overridden from an action by setting @title:

<title><%= @title || "Default Title Here" %></title>

Then you can generate a title in your action:

def show
  @post = Post.find_by_id params[:id]
  @title = "tybro's blog: #{@post.title}"
end


回答3:

I would do this:

# Application Controller
before_filter :set_page_title

private

def set_page_title
  @page_title = "Default Title"
end

overwrite it in your other controllers

# Users Controller
before_filter :set_page_title

def new # in Users controller
  ...
  @page_title = "Sign up"
  ...
end

private

def set_page_title
  @page_title = "Users"
end

In your view:

<title><%= h @page_title %></title>


回答4:

Have a look at Ryan Bates (ryanb from railscasts.com) nifty layout. He has a method in there that does what you are looking for. It's similar to Garrett's way, only he moves the default values in the helper too. Check out the helper.rb file and how he link textuses it.

You can install is as gem (and use the other nice features) or just use his way of doing it. You only need to pass the title value to title in each view (or let it fall to the default) and there you go. I'm with Garrett to put these things in the view.



回答5:

Layout template

In your layout (e.g. application.html.erb) add:

<title><%= content_for(:page_title) || "Fallback title" %></title>

Page template

In the page template you'd like to a specify a title from:

<%- content_for(:page_title, "Specific page title") %>