Rails 3 - Ideal way to set title of pages

后端 未结 13 1289
失恋的感觉
失恋的感觉 2020-12-04 06:33

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

app/views/layouts/application.html:


  

        
13条回答
  •  心在旅途
    2020-12-04 07:02

    I found that apeacox's solution didn't work for me (in Rails 3.0.3).

    Instead I did...

    In application_helper.rb:

    def title(page_title, options={})
      content_for(:title, page_title.to_s)
      return content_tag(:h1, page_title, options)
    end
    

    In the layout:

    <%= content_for(:title) %>
    

    In the view:

    <% title "Page Title Only" %>
    

    OR:

    <%= title "Page Title and Heading Too" %>
    

    Note, this also allows us to check for the presence of a title and set a default title in cases where the view hasn't specified one.

    In the layout we can do something like:

    <%= content_for?(:title) ? content_for(:title) : 'This is a default title' %>
    

提交回复
热议问题