Ruby on Rails 逐步进阶
STEP 2: 布局
为了使以后的开发能更加顺利地进行,稍微调整一下画面的版面吧。
首先生成布局用的HTML模板。
$ edit app/views/layouts/application.html.erb
这里首先使用编辑器进行一下上面所述的编辑源文件的操作。将edit 部分用你实际使用中的编辑器的命令(vi等)替换。使用IDE的情况下,用文件生成、编辑菜单等打开文件。
文件内容做如下编辑。
<!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" xml:lang="ja" lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><%= document_title %></title>
<%= stylesheet_link_tag 'application' %>
</head>
<body>
<div id="wrapper">
<%= render :partial => 'shared/header' %>
<div id="contents">
<%= yield %>
</div>
<%= render :partial => 'shared/footer' %>
</div>
</body>
</html>
接下来,生成在布局第6行使用的辅助方法document_title document_title ,以及之后将要用到的copyright 。
$ edit app/helpers/application_helper.rb
module ApplicationHelper
def document_title
if @document_title.present?
h(@document_title) + ' - Plaka'
else
'Plaka'
end
end
def copyright
text = 'Copyright © 2010'
if Date.today.year > 2010
text << '-' + Date.today.year.to_s
end
text << ' Oiax Inc., All Rights Reserved.'
text
end
end
然后生成标题用的局部模板 shared/header 。
$ mkdir app/views/shared $ edit app/views/shared/header.html.erb
<div id="header"> <%= link_to_unless_current 'Plaka', :root %> </div>
link_to_unless_current 是生成指向某一页面的超链接的方法。在第1参数指定链接字符串,第2参数指定链接对象。指定链接对象的方法多种多样,在这里是指定 :root 这个符号。
第一节在 config/routes.rb 增加了 map.root :controller => 'top', :action => 'index' 的描述。根据这个,Top控制器的index动作被命名为 :root 。
指向被命名动作的超链接,可以像这样简单的记述。
另外,link_to_unless_current ,指现在页面的URL同作为链接对象的页面的URL相同的情况下,并不返回超链接,只返回字符串。
同样,标题用的局部模板 shared/footer 也是。
$ edit app/views/shared/footer.html.erb
<div id="footer"> <%= copyright %> </div>
最后,生成层叠样式表 (CSS) 的文件,完成布局。
$ edit public/stylesheets/application.css
div#wrapper {
width: 600px;
margin: 10px auto;
border: solid 1px #666;
background-color: #066;
}
div#header, div#footer {
background-color: #000;
color: #ccc;
margin: 5px;
padding: 5px;
}
div#contents {
background-color: #fff;
color: #000;
margin: 5px;
padding: 5px;
}
刷新页面,变成下面画面。

(2010/01/29)
- 前言
- STEP 1: 从程序的生成到首页的显示 (2010/01/26)
- STEP 2: 布局 (2010/01/29)
- STEP 3: 记录列表 (2010/01/30)
- STEP 4: 记录详情显示与删除 (2010/01/31)

