Rails 3 - Ideal way to set title of pages

后端 未结 13 1255
失恋的感觉
失恋的感觉 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 06:50

    This is my preferred way of doing it:

    application_helper.rb

    module ApplicationHelper
      def title(*parts)
        content_for(:title) { (parts << t(:site_name)).join(' - ') } unless parts.empty?
      end
    end
    

    views/layouts/application.html.erb

    
      <%= content_for?(:title) ? yield(:title) : t(:site_name) %>
    
    

    config/locales/en.yml

    en:
      site_name: "My Website"
    

    This has the nice advantage to always falling back to the site name in your locales, which can be translated on a per-language basis.

    Then, on every other page (eg. on the About page) you can simply put:

    views/home/about.html.erb

    <% title 'About' %>
    

    The resulting title for that page will be:

    About - My Website

    Simples :)

提交回复
热议问题