- Ruby on Rails 教程
- Ruby on Rails - 首頁
- Ruby on Rails - 簡介
- Ruby on Rails - 安裝
- Ruby on Rails - 框架
- Ruby on Rails - 目錄結構
- Ruby on Rails - 示例
- Ruby on Rails - 資料庫設定
- Ruby on Rails - Active Records
- Ruby on Rails - 遷移
- Ruby on Rails - 控制器
- Ruby on Rails - 路由
- Ruby on Rails - 檢視
- Ruby on Rails - 佈局
- Ruby on Rails - 腳手架
- Ruby on Rails - AJAX
- Ruby on Rails - 檔案上傳
- Ruby on Rails - 傳送郵件
- Ruby on Rails 資源
- Ruby on Rails - 參考指南
- Ruby on Rails - 快速指南
- Ruby on Rails - 資源
- Ruby on Rails - 討論
- Ruby 教程
- Ruby 教程
Ruby on Rails - 佈局
佈局定義了 HTML 頁面的周圍環境。它是定義最終輸出的通用外觀和感覺的地方。佈局檔案位於 app/views/layouts 中。
此過程涉及定義佈局模板,然後讓控制器知道它的存在並使用它。首先,讓我們建立模板。
在 app/views/layouts 中新增一個名為 standard.html.erb 的新檔案。您透過檔名讓控制器知道要使用哪個模板,因此建議遵循相同的命名方案。
將以下程式碼新增到新的 standard.html.erb 檔案中並儲存更改 -
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = iso-8859-1" />
<meta http-equiv = "Content-Language" content = "en-us" />
<title>Library Info System</title>
<%= stylesheet_link_tag "style" %>
</head>
<body id = "library">
<div id = "container">
<div id = "header">
<h1>Library Info System</h1>
<h3>Library powered by Ruby on Rails</h3>
</div>
<div id = "content">
<%= yield -%>
</div>
<div id = "sidebar"></div>
</div>
</body>
</html>
您剛剛新增的所有內容都是標準的 HTML 元素,除了兩行。stylesheet_link_tag 輔助方法輸出一個樣式表 <link>。在本例中,我們連結了 style.css 樣式表。yield 命令讓 Rails 知道它應該放置此處呼叫的方法的 html.erb。
現在開啟 book_controller.rb 並將以下行新增到第一行下方 -
class BookController < ApplicationController layout 'standard' def list @books = Book.all end ...................
它指示控制器我們希望使用 standard.html.erb 檔案中提供的佈局。現在嘗試瀏覽書籍,這將生成以下螢幕。
新增樣式表
到目前為止,我們還沒有建立任何樣式表,因此 Rails 使用預設樣式表。現在讓我們建立一個名為 style.css 的新檔案並將其儲存在 /public/stylesheets 中。將以下程式碼新增到此檔案中。
body {
font-family: Helvetica, Geneva, Arial, sans-serif;
font-size: small;
font-color: #000;
background-color: #fff;
}
a:link, a:active, a:visited {
color: #CD0000;
}
input {
margin-bottom: 5px;
}
p {
line-height: 150%;
}
div#container {
width: 760px;
margin: 0 auto;
}
div#header {
text-align: center;
padding-bottom: 15px;
}
div#content {
float: left;
width: 450px;
padding: 10px;
}
div#content h3 {
margin-top: 15px;
}
ul#books {
list-style-type: none;
}
ul#books li {
line-height: 140%;
}
div#sidebar {
width: 200px;
margin-left: 480px;
}
ul#subjects {
width: 700px;
text-align: center;
padding: 5px;
background-color: #ececec;
border: 1px solid #ccc;
margin-bottom: 20px;
}
ul#subjects li {
display: inline;
padding-left: 5px;
}
現在重新整理瀏覽器並檢視區別 -
接下來是什麼?
下一章將解釋如何使用 Rails 腳手架開發應用程式,以允許使用者訪問資料庫中任何記錄的新增、刪除和修改。
廣告