針對上一節的新需求,界面設計師還為我們設計了一個新的界面,不僅僅是目錄頁,還包含了站點的整體風格,如下圖:
感謝界面設計師為我們提供的“又黑又硬”的工具條,這個看起來真的很酷。下面,讓我們來享用她的工作成果吧。
我們前面的scaffold已經生成了有繼承關系模板,顯然對於一些公用的內容應該放到base.html之中。但是我們先把這件事情放到一邊,先來實現目錄頁。
首選為目錄頁確定一個url,不妨叫做/depotapp/store,在depotapp的urls.py中增加一條pattern:
- (r'store/$', store_view),
而store_view是對應的視圖函數,在depotapp的views.py中定義:
- def store_view(request):
- products = Product.objects.filter(date_available__gt=datetime.datetime.now().date()) \
- .order_by("-date_available")
- t = get_template('depotapp/store.html')
- c = RequestContext(request,locals())
- return HttpResponse(t.render(c))
store_view使用depotapp/store.html作為模板:
depot/templates/depotapp/store.html
- {% extends "base.html" %}
- {% block title %} 產品目錄 {% endblock %}
- {% block pagename %} 產品目錄 {% endblock %}
- {% block content %}
- {% for item in products %}
- <divclass="row"style="padding-top:10">
- <divclass="span3 media-grid">
- <ahref="#">
- <imgclass="thumbnail"src="{{item.image_url}}"alt="">
- </a>
- </div>
- <divclass="span-two-thirds">
- <h3>{{item.title}}</h3>
- <br/>
- {{item.description}}
- <br/>
- <br/>
- <br/>
- <divclass="row">
- <divclass="span2"><h3>¥{{item.price|floatformat:"2"}}</h3></div>
- <divclass="span"><aclass="btn primary"href="#">加入購物車</a></div>
- </div>
- </div>
- </div>
- <divclass="page-header">
- </div>
- {% endfor %}
- {% endblock %}
該模板繼承了base.html,在base模板中實現了整個站點的基礎布局:
depot/templates/base.html
- <htmlxmlns="http://www.w3.org/1999/xhtml">
- <head>
- <metahttp-equiv="Content-Type"content="text/html; charset=utf-8">
- <metaname="description"content="a depot implement with Django"/>
- <metaname="keywords"content="django,depot"/>
- <metaname="author"content="Holbrook(http://hi.csdn.net/space-2668.html)"/>
- <title>{% block title %} 標題 {% endblock %}</title>
- <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
- <!--[if lt IE 9]>
- <scriptsrc="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
- <![endif]-->
- <!-- Le styles -->
- <linkrel="stylesheet"href="/static/css/bootstrap.min.css">
- <linkrel="stylesheet"href="/static/css/layout.css">
- </head>
- <body>
- <divclass="topbar">
- <divclass="fill">
- <divclass="container">
- <aclass="brand"href="#">Depot</a>
- <ulclass="nav">
- <liclass="active"><ahref="#">首頁</a></li>
- <li><ahref="#about">問題</a></li>
- <li><ahref="#contact">新聞</a></li>
- <li><ahref="#contact">聯系我們</a></li>
- </ul>
- <formaction=""class="pull-right">
- <inputclass="input-small"type="text"placeholder="用戶名">
- <inputclass="input-small"type="password"placeholder="密碼">
- <buttonclass="btn"type="submit">登錄</button>
- </form>
- </div>
- </div>
- </div>
- <divclass="container">
- <divclass="content">
- <divclass="page-header">
- <h1>{% block pagename %} 頁面名稱 {% endblock %}</h1>
- </div>
- {% block content %}
- 內容
- {% endblock %}
- </div><!-- /content -->
- </div><!-- /container -->
- </body>
- </html>
這樣,我們用很少的代碼就實現了新增一個目錄頁,並且為整個站點設置了統一的布局。