Rails: Cómo cambiar el título de una página?


¿Cuál es la mejor manera de crear un título personalizado para páginas en una aplicación Rails sin usar un plug-in?

Author: Flip, 2008-10-09

14 answers

En tus vistas haz algo como esto:

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

Lo siguiente va en el archivo de diseño:

<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>

También es posible encapsular las sentencias content_for y yield(:title) en métodos auxiliares (como otros ya han sugerido). Sin embargo, en casos simples como este me gusta poner el código necesario directamente en las vistas específicas sin ayudantes personalizados.

 225
Author: Christoph Schiessl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-08 12:38:12

Aquí hay una opción simple que me gusta usar

En su diseño

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

Y en la parte superior de la plantilla de la página (primera línea)

<% @title="Home" %>

Debido a la forma en que se analizan el diseño y las plantillas de página, se evalúa @title="Home" antes de procesar el diseño.

 113
Author: opsb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-26 13:56:59

La mejor práctica es utilizar content_for.

Primero, agregue un par de métodos auxiliares (es decir. stick en 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

Luego, en su vista de diseño, simplemente puede usar:

<title><%= page_title %></title>

...y en la vista misma:

<%= page_heading "Awesome" %>

Esta forma tiene la ventaja de permitirle barajar donde se pega la etiqueta h1 para su título, y mantiene su controlador agradable y libre de molestos variables @title.

 48
Author: Aupajo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-31 02:11:54

Una mejora sobre @opsb y una forma más completa de @FouZ ' s:

En application.html.erb:

<title><%= @title || "Default Page Title" %></title>

En el archivo erb de la vista o su controlador:

<% @title = "Unique Page Title" %>
 19
Author: boulder_ruby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-21 10:32:29
 13
Author: Avdi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-09 05:01:11

Sin más detalles sobre el caso de uso o los requisitos que está tratando de satisfacer, se me ocurren varias alternativas:

1) Cambie el título en una de sus páginas de diseño y consuma un método auxiliar almacenado en application_helper.rb

<title><%= custom_title %></title>

Este enfoque le dará un título único para cada página de diseño.

2) Railscasts sugiere usar un parcial para cargar lo que aparece entre las etiquetas de la CABEZA

3) Use llamadas javascript / ajax para manipular el DOM si necesita cambiar título después del evento load.

Tal vez no quieras cambiar el contenido etiquetado por el elemento title. Tal vez realmente necesite una migaja de ruta de algún tipo, para que sus usuarios siempre sepan dónde están con respecto a la jerarquía de navegación de su sitio. Si bien me ha ido bien con cómo el complemento de Goldberg, estoy seguro de que hay otras formas de lograr la misma funcionalidad.

 6
Author: Alan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-09 05:06:09

Utilizo nifty_generator's "nifty_layout" que proporciona una variable de título que puedo llamar a continuación en la página usando:

<% title "Title of page" %>

También puedo usar <% title "Title of page", false %> para que el título solo se muestre en el título del navegador y no en la página en sí.

 3
Author: sent-hil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-04 13:19:13

También puede configurarlo en un before_filter en su controlador.

# 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>

Luego puede establecer condiciones en el método set_title para establecer títulos diferentes para diferentes acciones en el controlador. Es bueno poder ver todos los títulos de página relevantes dentro de su controlador.

 2
Author: JasonOng,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-09 07:12:16

La mejor manera / limpia de hacer esto :

<title><%= @page_title or 'Page Title' %></title>
 0
Author: FouZ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-06 03:41:34
 0
Author: Henrik N,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-16 13:08:11

Enfoque para la titulación de páginas utilizando el método content_for y un {[4 parcial]}

1 . parcial nombre : _page_title.HTML.erb

<%content_for :page_title do %>
 <%=title%>
<%end%>

2 . Uso en la aplicación.HTML.erb inside title tag

   <title><%=yield :page_title %></title>

3 . Uso en el respectivo *.HTML.erb excluida la aplicación.HTML.erb Pon esto en cualquiera .HTML.erb and supply título de la página

    e.g : inside index.html.erb

    <%=render '_page_title', title: 'title_of_page'%>
 0
Author: Kofi Asare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-02 09:21:33

En resumen, puedo escribir esto de la siguiente manera

<%content_for :page_title do %><%= t :page_title, "Name of Your Page" %> <% end %>
 0
Author: Mukesh Kumar Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-25 05:30:14

Me gusta el método de opsb, pero este método también funciona.

<% provide(:title,"ttttttttttttttttttZ") %>
<html>
  <head><title><%= yield(:title) %></title></head>
   <body></body>
</html>
 0
Author: barlop,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-14 00:27:04

Me gustaría añadir mi variante bastante simple.

En ApplicationController defina este método:

  def get_title
    @action_title_name || case controller_name
                            when 'djs'
                              'Djs'
                            when 'photos'
                              'Photos'
                            when 'events'
                              'Various events'
                            when 'static'
                              'Info'
                            when 'club'
                              'My club'
                            when 'news'
                              'News'
                            when 'welcome'
                              'Welcome!'
                            else
                              'Other'
                          end
  end

Después de eso, puede llamar a get_title desde la etiqueta de título de su diseño. Puede definir un título más específico para su página definiendo la variable @action_title_name en sus acciones.

 -9
Author: IDBD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-09 18:33:29