Django开发网站(三)
模板详述
{% tag%} {%endtag%}
{{variable}}
{# comment#}
模板变量:
t=template.loader.get_template('bar.html')
c=template.Context({'var':value})
html=t.render(c)
return HttpResponse(html)
解析:
第1句是加载一个已有的模板,其中这个模板中含有变量var,如{{var}};
第2句是生成上下变量,该变量可以是字典、属性、方法或列表,其中在模板中分别调用形式为foo['bar']、foo.bar、foo.bar()、foo[bar]
第3句是将变量值渲染到模板中,
第4句是返回响应
其实上面的4句可以简写成1句:
return render_to_response('bar.html',{'var':value})或
return render_to_response('bar.html',locals())
模板标签:
if标签
{% if is_ture %}
.....
{% else %}
.....
{% endif %}
for标签
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
empty标签
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% empty %}
<li>Sorry, no athlete in this list!</li>
{% endfor %}
ifequal标签
{% ifequal user.id comment.user_id %}
...
{% endifequal %}
ifchanged标签
{% for date in days %}
{% ifchanged date.date %} {{ date.date }} {% endifchanged %}
{% ifchanged date.hour date.date %}
{{ date.hour }}
{% endifchanged %}
{% endfor %}
with标签
{% with business.employees.count as total %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
模板继承:
block标签
base.html
{% block title %}{% endblock %}
extends.html
{% extends "base.html" %}
{% block title %}My to-do list{% endblock %}
浙公网安备 33010602011771号