Agile Web Development with Rails 3nd Edition學習筆記-創建頁面佈局模板

典型的網站一般都具有一致的佈局,ASP.NET中使用TemplatePage就提供了一個做到這件事的途徑。它使得每個頁面都在一個確定的頁面框架中顯示。那麼,Rails中能否做到,又是如何做到這一點的呢?
這一節的內容就要說明這個問題。
在Rails中,每一個Controller都可以有一個與之對應的Layout文件,這個文件保存在app/views/layouts目錄中。我們就可以通過這個Layout文件來做到這一點。
首先,我們爲store來創建一個Layout文件。名字是store.html.erb,並把它保存到app/views/layouts目錄下。並在該文件中添加如下代碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Pragprog Books Online Store</title>
<!-- START:stylesheet -->
<%= stylesheet_link_tag "depot", :media => "all" %>
<!-- END:stylesheet -->
</head>
<body id="store">
<div id="banner">
<%= image_tag("logo.png") %>
<%= @page_title || "Pragmatic Bookshelf" %>
</div>
<div id="columns">
<div id="side">
<a href="http://www....">Home</a><br />
<a href="http://www..../faq">Questions</a><br />
<a href="http://www..../news">News</a><br />
<a href="http://www..../contact">Contact</a><br />
</div>
<div id="main">
<%= yield :layout %>
</div>
</div>
</body>
</html>

這個文件將被store的每一個頁面所使用。
該文件中,第7行的代碼加載了我們的樣式表文件depot.css。[color=orange](但是:media => all)是什麼意思呢?[/color]
第13行使用“Pragmatic Bookshelf”作爲@page_title的值,顯示在頁面標題部分。[color=orange](但是他們之間的“||”是什麼意思呢?)[/color]
第23行實際上是要顯示我們的頁面內容的位置,yield執行時將會把實際的頁面加載到這裏。[color=orange](這裏的:layout的作用是什麼呢?)[/color]

接下來,我們需要定義這個模板頁面的樣式表。我們可以把下面的內容添加到我們depot.css文件中:
#ba nner {
background: #9c9 ;
padding-top: 10px;
padding-bottom: 10px;
border-bottom: 2px solid;
font: small-caps 40px/40px "Times New Roman", serif;
color: #282 ;
text-align: center;
}
#ba nner img {
float: left;
}
#c olumns {
background: #141 ;
}
#main {
margin-left: 13em;
padding-top: 4ex;
padding-left: 2em;
background: white;
}
#side {
float: left;
padding-top: 1em;
padding-left: 1em;
padding-bottom: 1em;
width: 12em;
background: #141 ;
}
#side a {
color: #bfb ;
font-size: small;
}


好了,我們現在可以看看我們添加模板頁面之後的效果了。同樣在啓動服務器之後,在瀏覽器的地址欄中輸入“http://localhost:3000/store”來顯示store的index頁面。結果如下圖:
[img]http://dl.iteye.com/upload/attachment/236468/87d4491a-f492-3c0d-a8e7-d5df6464f72a.jpg[/img]
怎麼樣是不是和上一篇中做到效果有了很大的變化。哈哈!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章