有了上一節關於Django模板的基礎,改造界面就很容易理解了。將界面設計師設計的頁面中的內容根據復用程度分別放到基礎模板base.html和專用模板productlist.html中。
depot/templates/base.html
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="description" content="a depot implement with Django"/> <meta name="keywords" content="django,depot" /> <meta name="author" content="Holbrook(http://hi.csdn.net/space-2668.html)" /> <title>{% block title %} 標題 {% endblock %}</title> <link rel="stylesheet" href="/static/css/bootstrap.min.css"> </head> <body> <div class="container"> {% block content %} 內容 {% endblock %} </div> </body> </html>
base作為整個網站的基礎布局,包含了所有頁面都需要的bootstrap.min.css。同時設置了兩個內容塊(title, content)。在productlist.html中替換這兩個內容塊:
depot/templates/depotapp/list_product.html
{% extends "base.html" %} {% block title %} 產品清單 {% endblock %} {% block content %} <div class="container"> <div class="page-header"> <h2>產品清單</h2> </div> {% for item in list_items.object_list %} <div class="row" style="padding-top:10"> <div class="span3 media-grid"> <a href="#"> <img class="thumbnail" src="{{item.image_url}}" alt=""> </a> </div> <div class="span-two-thirds"> <h4>{{item.title}}</h4> {{item.description}} </div> <div class="span2" style="align:right"> <p><a class="btn primary" href="{% url depotapp.views.view_product item.id %}">查看</a></a> </p> <p><a class="btn success" href="{% url depotapp.views.edit_product item.id %}">編輯</a> </p> <p><a class="btn danger" href="#">刪除</a></p> </div> </div> {% endfor %} {% if list_items.has_previous %} <a href="?page={{ list_items.previous_page_number }}">上一頁</a> {% endif %} <span class="current"> 第{{ list_items.number }}頁,共{{ list_items.paginator.num_pages }}頁 </span> {% if list_items.has_next %} <a href="?page={{ list_items.next_page_number }}">下一頁</a> {% endif %} <p> <a href="{% url depotapp.views.create_product %}">新增產品</a> </p> {% endblock %}
先是聲明這個模板繼承自base.html,然后是兩個內容塊的實現。
注意其中鏈接的寫法:href="{% url depotapp.views.view_product item.id %}"。這樣定義的href是關聯到view函數,而不是硬編碼的URL。在以后如果改變了URLconf的定義,不需要再更改模板。這個功能不是rails特有的!
關於分頁的部分,無需關注,以后再說。
最后,認真填寫一下表單,將真正的數據存到數據庫,就可以在http://localhost:8000/depotapp/product/list/ 看到漂亮的界面了。
例子中使用的書籍信息和圖片鏈接均來自豆瓣讀書