1.blog.views.py # Create your views here. from django.template import loader,Context from django.http import HttpResponse from blog.models import BlogPost def archive(request): posts = BlogPost.objects.all() t = loader.get_template('archive.html') c = Context({'posts': posts}) return HttpResponse(t.render(c)) 2.archive.html {% extends "base.html" %} {% block content %} {% for post in posts %} <h1>{{ post.title|truncatewords:"30"}}</h1> <p>{{ post.content }}</p> <p>{{ post.timestamp|date:"1, F jS"}}</p> {% endfor %} {% endblock %} 3.base.html <html> <style type="text/css"> body { color: #edf; background: #453; padding: 0 5em; margin:0 } h1 { padding: 2em lem; background:#675 } h2 { color: #bf8; border-top: 1px dotted #fff; margin-top: 2em } p { margin: lem 0 } </style> <body> <h1><center>Blog</center></h1> {% block content %} {% endblock %} </body> </html> 一。標籤 用{% %}表示,用於處理一些邏輯 常用的幾個標籤 {% if %}和{% endif %} {% for %}和{% endfor %} {% for %}標籤允許你按順序遍歷一個序列中的各個元素 Python的for語句語法爲for X in Y,X是用來遍歷Y的變量 每次循環模板系統都會渲染{% for %}和{% endfor %}之間的所有內容 二。註釋 和HTML或編程語言如Python一樣,Django模板語言允許註釋{# #},如: 代碼 {# This is a blog #} 三。過濾器 {{ post.title|truncatewords:"30"}} 這將顯示bio標量的前30個字,過濾器參數一直使用雙引號 使用(|)管道來申請一個過濾器 四。引用變量 變量的形式:{{ variable }} 如上例中的{{ post.content }} {{ post.content }} 會被 post 對象的 content 屬性替換 使用句點 “.” 可以訪問變量的屬性.
母板:{% block title %}{% endblock %}
如上面base.html的
{% block content %} {% endblock %}
子板:{% extends "base.html" %}
{% block conttent %}{% endblock %}