Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

html - rails page titles

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}" %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...