Rails 3 - Ideal way to set title of pages

后端 未结 13 1256
失恋的感觉
失恋的感觉 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:57

    I prefer this:

    module ApplicationHelper
      def title(*page_title)
        if Array(page_title).size.zero?
          content_for?(:title) ? content_for(:title) : t(:site_name)
        else
          content_for :title, (Array(page_title) << t(:site_name)).join(' - ')
        end
      end
    end
    

    If title is called without arguments, it returns the current value of title or the default which in this example will be "Example".

    It title is called with arguments, it sets it to the passed value.

    # layouts/application.html.erb
    <%= title %>
    
    # views/index.html.erb
    <% title("Home") %>
    
    # config/locales/en.yml
    en:
      site_name: "Example"
    

提交回复
热议问题