(略去add_test_data方法)
也许这个下面这个自动生成的页面入不了你的法眼,我们稍微运用css来对页面做些许更改。
最终我们会得到一个html样式的页面,其中使用css来定义显示风格。首先我们找个地方放下css样式定义。
rails默认的应用程序都会使用public\stylesheets目录下面的scaffold.css样式表。我们新建一份样式表,放在同一目录下。这是它的下载地址。 https://files.cnblogs.com/acnono/depot.css(右键-->另存为)
app\views\layouts目录下面存放着页面的布局模板。其中css样式表就是在这里被引用的,我们讲depot样式表添加到引用里面去。
原来的appviews/layouts/products.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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Products: <%= controller.action_name %></title>
<%= stylesheet_link_tag 'scaffold' %>
</head>
<body>
<p style="color: green"><%= flash[:notice] %></p>
<%= yield %>
</body>
</html>
添加depot后(下划线加粗部分):
<!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="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Products: <%= controller.action_name %></title>
<%= stylesheet_link_tag 'scaffold', 'depot' %>
</head>
<body>
<p style="color: green"><%= flash[:notice] %></p>
<%= yield %>
</body>
</html>
我们把depot.css放在public\stylesheets下面,然后用一个简单的表格状模板替代掉现在的列表页index.html.erb。
app/views/products/index.html.erb
<div id="product-list">
<h1>Listing products</h1>
<table cellpadding="5" cellspacing="0">
<% for product in @products %>
<tr valign="top" class="<%= cycle('list-line-odd', 'list-line-even') %>">
<td>
<%= image_tag product.image_url, :class => 'list-image' %>
</td>
<td width="60%">
<span class="list-title"><%=h product.title %></span><br />
<%=h truncate(product.description.gsub(/<.*?>/,''), 80) %>
</td>
<td class="list-actions">
<%= link_to 'Show', product %><br/>
<%= link_to 'Edit', edit_product_path(product) %><br/>
<%= link_to 'Destroy', product,
:confirm => 'Are you sure?',
:method => :delete %>
</td>
</tr>
<% end %>
</table>
</div>
<br />
<%= link_to 'New product', new_product_path %>
刷新products页面。
这里我们注意到,我们输入的image_url已经以图片的形式输出在页面上面了。
这里与以前不同的是,我们在之前是用agile.jpg类似的名称来保存。而原来的agile.jpg就放在public\images目录下面。以前似乎需要保存images\agile.jpg才能引用到保存的图片。