Rails: How to change the title of a page?

前端 未结 15 1225
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 17:08

What is the best way to create a custom title for pages in a Rails app without using a plug-in?

相关标签:
15条回答
  • 2020-11-30 17:43

    This simple approach sets a default title, but also let you override it whenever you please.

    In app/views/layouts/application.html.erb:

    <title><%= yield(:title) || 'my default title' %></title>
    

    And to override that default, place this in any view you like

    <% content_for :title, "some new title" %>
    
    0 讨论(0)
  • 2020-11-30 17:46

    You can also set it in a before_filter in your controller.

    # foo_controller.rb
    
    class FooController < ApplicationController
    
      before_filter :set_title
    
      private
    
      def set_title
        @page_title = "Foo Page"
      end
    
    end
    
    # application.html.erb
    
    <h1><%= page_title %></h1>
    

    You can then set conditions in the set_title method to set a different titles for different actions in the controller. It's nice to be able to see all the relevant page titles within your controller.

    0 讨论(0)
  • 2020-11-30 17:46

    In short, I can write this down as follow

    <%content_for :page_title do %><%= t :page_title, "Name of Your Page" %> <% end %>
    
    0 讨论(0)
提交回复
热议问题