RailsCase30 Pretty Page Title 動態變化的網頁標題

來源:互聯網
上載者:User

標籤:des   style   http   os   io   使用   ar   for   檔案   

幾乎所有的Rails網站都使用layout,但這回造成所有的網頁都有同樣的標題(在header中的title)。為每個網頁設定專屬的標題並不是件困難的事,解決方案見下文。

初步嘗試
ruby<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">  <head>    <title>ASCIIcasts</title>    <%= stylesheet_link_tag ’asciicasts’ %>…

這是ASCIIcasts layout的部分代碼。title元素已經被寫死,故每個頁面的title都是相同的。

下面為首頁的代碼,下一步將展示如何使首頁擁有自己的title。

ruby<h2>Recent Episodes</h2><ol class="episodeList"><% @episodes.each do |episode| %>  <%= render :partial=>’episode_item’, :locals => {:episode => episode} %><% end %></ol>

我們可利用content_for函數來實現此功能。在每個頁面均添加如下代碼:

ruby<% content_for :title do %>Recent Episodes<% end %>

在layout中添加如下代碼,用來顯示title

ruby<title>ASCIIcasts - <%= yield :title %></title>
重新整理網頁,展示如下:


在每個頁面中,都要加入包含content_for的代碼,這並不是優雅的處理方式。另一種處理方式是,在每個頁面均設定一個執行個體變數,在layout中將其展示出來。我們將用<% @page_title = "Recent Episodes" %>來代替content_for,並更新layout中的內容:

ruby<title>ASCIIcasts - <%= @page_title %></title>

上述方式仍不是一個好的方式。

使用Helper方法

最清爽的解決方案是在application_helper中建立名為title的方法,此方法接收一個要展示title內容的參數。

rubymodule ApplicationHelper  def title(page_title)    content_for(:title) { page_title }  endend
再此,繼續使用content_for,使得layout可用yeild展示title。

layout中的代碼如下:

ruby<title>ASCIIcasts - <%= yield :title %></title>

每個頁面的代碼如下:
ruby<% title "Recent Episodes" %>
設定預設值

可能不是每一個頁面都要不同的title,此時設定預設值是可行的。按如下方式修改layout檔案

ruby<title>ASCIIcasts - <%= yield (:title) || "video.to_s" %></title>

若title在頁面中沒有被設定,將展示預設值。

一個小技巧

有一些可以精簡代碼的小技巧。若網站中,每個頁面的開頭都有h2元素,h2中顯示的內容即為title,可將每個頁面的重複代碼轉移至layout的頂部。涉及的layout大體如下:

ruby<div class="main">  <h2><%= yield(:title) %></h2>  <%= yield %></div>
展示的頁面如下:


原文地址:http://railscasts.com/episodes/30-pretty-page-title?view=asciicast



RailsCase30 Pretty Page Title 動態變化的網頁標題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.