`
tiny.strimp
  • 浏览: 29399 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

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。(但是:media => all)是什么意思呢?
第13行使用“Pragmatic Bookshelf”作为@page_title的值,显示在页面标题部分。(但是他们之间的“||”是什么意思呢?)
第23行实际上是要显示我们的页面内容的位置,yield执行时将会把实际的页面加载到这里。(这里的:layout的作用是什么呢?)

接下来,我们需要定义这个模板页面的样式表。我们可以把下面的内容添加到我们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页面。结果如下图:

怎么样是不是和上一篇中做到效果有了很大的变化。哈哈!
  • 大小: 226.2 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics