Rails 3 - Ideal way to set title of pages

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

    I have a somewhat more complicated solution. I want to manage all of my titles in my locale files. I also want to include meaningful titles for show and edit pages such that the name of the resource is included in the page title. Finally, I want to include the application name in every page title e.g. Editing user Gustav - MyApp.

    To accomplish this I create a helper in application_helper.rb which does most of the heavy lifting. This tries to get a name for the given action from the locale file, a name for the assigned resource if there is one and combines these with the app name.

    # Attempt to build the best possible page title.
    # If there is an action specific key, use that (e.g. users.index).
    # If there is a name for the object, use that (in show and edit views).
    # Worst case, just use the app name
    def page_title
      app_name = t :app_name
      action = t("titles.#{controller_name}.#{action_name}", default: '')
      action += " #{object_name}" if object_name.present?
      action += " - " if action.present?
      "#{action} #{app_name}"
    end
    
    # attempt to get a usable name from the assigned resource
    # will only work on pages with singular resources (show, edit etc)
    def object_name
      assigns[controller_name.singularize].name rescue nil
    end
    

    You will need to add action specific texts in your locale files in the following form:

    # en.yml 
    titles:
      users:
        index: 'Users'
        edit: 'Editing'
    

    And if you want to use meaningful resource names in your singular views you may need to add a couple of proxy methods, e.g.

    # User.rb
    def name
      username
    end
    

提交回复
热议问题