views:

27

answers:

2

Whats the proper way to set the page title in rails 3. Currently I'm doing the following:

app/views/layouts/application.html .... <%= render_title %> <%= csrf_meta_tag %> ....

app/helpers/application_helper.rb ... def render_title return @title if defined?(@title) "Generic Page Title" end ...

app/controllers/some_controller.rb ... def show @title = "some custom page title" ... end ...

Is there another/better way of doing the above?

A: 

you could a simple helper:

def title(page_title)
    @content_for_title = page_title.to_s
end

use it in your layout:

<title><%= yield(:title) %></title>

then call it from your templates:

<% title "Your custom title" %>

hope this helps ;)

apeacox
A: 

@akfalcon - I use a similar strategy, but without the helper.. I just set the default @title in the application controller and then use, <%=@title%> in my layout. If I want to override the title, I set it again in the controller action as you do. No magic involved, but it works just fine. I do the same for the meta description & keywords.

I am actually thinking about moving it to the database so an admin could change the titles,etc without having to update the Rails code. You could create a PageTitle model with content, action, and controller. Then create a helper that finds the PageTitle for the controller/action that you are currently rendering (using controller_name and action_name variables). If no match is found, then return the default.

@apeacox - is there a benefit of setting the title in the template? I would think it would be better to place it in the controller as the title relates directly to the action being called.

cowboycoded
@cowboycoded: It's not a good practice to set a title inside a controller because the former is about View and the latter is about business logic. For example, having a 'blog' controller, it's normal to set a title according to the post.title and there's no reason to make this in controller, but you make it in template or layout file
apeacox