Rails: How to change the title of a page?

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

    The best/clean way to do this :

    <title><%= @page_title or 'Page Title' %></title>
    
    0 讨论(0)
  • 2020-11-30 17:23

    Look into content_for: http://railscasts.com/episodes/8

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

    Here's a simple option that I like to use

    In your layout

    <head>
      <title><%= @title %></title>
    </head>
    

    And at the top of your page template (first line)

    <% @title="Home" %>
    

    Because of the way the layout and page templates are parsed the @title="Home" is evaluated before the layout is rendered.

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

    I use nifty_generator's "nifty_layout" which provides with a title variable which I can call then on the page using:

    <% title "Title of page" %>

    I can also user <% title "Title of page", false %> to have the title just show in browser title and not in the page itself.

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

    In your views do something like this:

    <% content_for :title, "Title for specific page" %>
    <!-- or -->
    <h1><%= content_for(:title, "Title for specific page") %></h1>
    

    The following goes in the layout file:

    <head>
      <title><%= yield(:title) %></title>
      <!-- Additional header tags here -->
    </head>
    <body>
      <!-- If all pages contain a headline tag, it's preferable to put that in the layout file too -->
      <h1><%= yield(:title) %></h1>
    </body>
    

    It's also possible to encapsulate the content_for and yield(:title) statements in helper methods (as others have already suggested). However, in simple cases such as this one I like to put the necessary code directly into the specific views without custom helpers.

    0 讨论(0)
  • 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:

    <title><%= page_title %></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.

    0 讨论(0)
提交回复
热议问题