Rails: How to change the title of a page?

前端 未结 15 1304
没有蜡笔的小新
没有蜡笔的小新 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:30

    Best practice is to use content_for.

    First, add a couple of helper methods (ie. stick in app/helpers/application_helper.rb):

    def page_title(separator = " – ")
      [content_for(:title), 'My Cool Site'].compact.join(separator)
    end
    
    def page_heading(title)
      content_for(:title){ title }
      content_tag(:h1, title)
    end
    

    Then in your layout view you can simply use:

    <%= page_title %>
    

    ...and in the view itself:

    <%= page_heading "Awesome" %>
    

    This way has the advantage of allowing you to shuffle where you stick the h1 tag for your title, and keeps your controller nice and free of pesky @title variables.

提交回复
热议问题