The following is the code for the home page, and the next step shows how to make the home page own title.
Ruby
We can use content_for
functions to implement this function. Add the following code to each page:
ruby<% content_for:title do%>recent episodes<% end%>
Add the following code to the layout to display the title
Ruby<title>asciicasts-<%= Yield:title%></title>
Refresh the page to show the following:
In each page, the included code is added content_for
, which is not an elegant way to handle it. Another way to do this is to set an instance variable on each page and display it in layout. <% @page_title = "Recent Episodes" %>
instead of Content_for, we'll update the content in layout:
Ruby<title>asciicasts-<%= @page_title%></title>
The above approach is still not a good way.
Using helper methods
The most refreshing solution is to application_helper
create a method named title in, which receives a parameter to show the title content.
Rubymodule applicationhelper def title (page_title) content_for (: title) {Page_title} endend
Again, continue to usecontent_for
, so that layout can display title yeild.
The code in layout is as follows:
Ruby<title>asciicasts-<%= Yield:title%></title>
The code for each page is as follows:
ruby<% title "Recent episodes"%>
Set default values
It may not be a different title for each page, and setting the default value is possible at this time. Modify the layout file as follows
Ruby<title>asciicasts-<%= Yield (: title) | | "Video.to_s"%></title>
If the title is not set in the page, the default value is displayed.
A little trick
There are some tips to streamline your code. If the site has H2 elements at the beginning of each page, the content displayed in H2 is title, and the duplicate code for each page can be transferred to the top of the layout. The layout involved is broadly as follows:
Ruby<div class= "main" >
The following pages are displayed:
Original address: Http://railscasts.com/episodes/30-pretty-page-title?view=asciicast
RailsCase30 Pretty page title dynamically changing pages titles