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 %}
原文:http://ysheng0806.blog.51cto.com/1557192/1767025