def current_time(req):
import datetime
now = datetime.datetime.now()
html = 'It is now %s.' % now
# django模板修改的视图函数
from django.template import Template,Context
now = datetime.datetime.now()
t = '<html><body>It is now %s.</body></html>' % now
c = Context({'current_date': str(now)})
html = t.render(c)
return HttpResponse(html)
# 另一种写法
import datetime
now = datetime.datetime.now()
return render(req,'current_datetime.html',{'current_date': str(now)[:19]})</code></pre>
模板语法终点:
变量:{{ 变量名 }}
深度查询,用点语法
过滤器
标签:{{ % % }}
在 Django 模板中遍历复杂数据结构的关键是点语法
def template_test(request):
name = 'lqz'
li = ['lqz',1,'18']
dic = {'name': 'lqz','age': 18}
ll2 = [
{'name': 'lqz','age': 18},{'name': 'lqz2','age': 19},{'name': 'egon','age': 20},{'name': 'kevin','age': 23}
]
ll3=[]
class Person:
def __init__(self,name):
self.name = name
标签看起来像是这样的:{% tag %}。标签比变量更加复杂:一些在输出中创建文本,一些通过循环或逻辑来控制流程,一些加载其后的变量将使用到的额外信息到模板中。一些标签需要开始和结束标签(例如{% tag %}...标签 内容... {% endtag %})。
遍历每一个元素:
{% for person in person_list %}
{{ person.name }}
{% endfor %}
可以利用{% for obj in list reversed %}反向完成循环。
遍历一个字典:
{% for key,val in dic.items %}
{{ key }}:{{ val }}
{% endfor %}
注:循环序号可以通过``{{ forloop }}显示
forloop.counter The current iteration of the loop (1-indexed) 当前循环的索引值(从1开始)
forloop.counter0 The current iteration of the loop (0-indexed) 当前循环的索引值(从0开始)
forloop.revcounter The number of iterations from the end of the loop (1-indexed) 当前循环的倒序索引值(从1开始)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed) 当前循环的倒序索引值(从0开始)
forloop.first True if this is the first time through the loop 当前循环是不是第一次循环(布尔值)
forloop.last True if this is the last time through the loop 当前循环是不是最后一次循环(布尔值)
forloop.parentloop 本层循环的外层循环
for 标签带有一个可选的{% empty %} 从句,以便在给出的组是空的或者没有被找到时,可以有所操作。
{% for person in person_list %}
{{ person.name }}
{% empty %}
sorry,no person here
{% endfor %}
{% if %}会对一个变量求值,如果它的值是“True”(存在、不为空、且不是boolean类型的false值),对应的内容块会输出。