def current_datetime(request):
now = datetime.datetime.now()
html = "It is now %s." % now
return HttpResponse(html)
你可能已经注意到我们在例子视图中返回文本的方式有点特别。 也就是说,HTML被直接硬编码在 Python代码之中
尽管这种技术便于解释视图是如何工作的,但直接将HTML硬编码到你的视图里却并不是一个好主意。 让我们来看一下为什么:
def current_time(req):
# ================================原始的视图函数
# import datetime
# now=datetime.datetime.now()
# html="现在时刻:%s.
" %now
# ================================django模板修改的视图函数
# from django.template import Template,Context
# now=datetime.datetime.now()
# t=Template('现在时刻是:{{current_date}}
')
# #t=get_template('current_datetime.html')
# 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]})
# 这样写就将处理过的now传到了current_datetime.html中,在html中就可以做相应的使用和处理了
模版语法重点:
变量:{{ 变量名 }} 放到{{ }}里面相当于执行了print, 所以里边最终都是字符串
1 深度查询 用点语法,可以连点, 深度查询时不可以加括号
2 过滤器
标签:{{% % }}
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
def test(self):
print('test函数')
return 11
@classmethod
def test_classmethod(cls):
print('类方法')
return '类方法'
@staticmethod
def static_method():
print('静态方法')
return '静态方法'
lqz = Person('lqz')
egon = Person('egon')
person_list = [lqz, egon]
bo = True
te = test()
import datetime
now=datetime.datetime.now()
link1='点我'
from django.utils import safestring
link=safestring.mark_safe(link1)
# html特殊符号对照表(http://tool.chinaz.com/Tools/htmlchar.aspx)
# 这样传到前台不会变成特殊字符,因为django给处理过了
dot='♠'
# return render(request, 'template_index.html', {'name':name,'person_list':person_list})
return render(request, 'template_index.html', locals())
模板中的 html文件 {{ name }}
{{ li }}
{{ dic }}
{{ lqz }}
{{ person_list }}
{{ bo }}
{{ te }}
深度查询句点符
{{ li.1 }}
{{ dic.name }}
{{ lqz.test }}
{{ lqz.name }}
{{ person_list.0 }}
{{ person_list.1.name }}
过滤器
{#注意:冒号后面不能加空格#}
{{ now | date:"Y-m-d H:i:s" }}
{#如果变量为空,设置默认值,空数据,None,变量不存在,都适用#}
{{ name |default:'数据为空' }}
{#计算长度,只有一个参数#}
{{ person_list |length }}
{#计算文件大小#}
{{ 1024 |filesizeformat }}
{#字符串切片,前闭后开,前面取到,后面取不到#}
{{ 'hello world lqz' |slice:"2:-1" }}
{{ 'hello world lqz' |slice:"2:5" }}
{#截断字符,至少三个起步,因为会有三个省略号(传负数,1,2,3都是三个省略号)#}
{{ '刘清政 world lqz' |truncatechars:"4" }}
{#截断文字,以空格做区分,这个不算省略号#}
{{ '刘清政 是 大帅比 谢谢' |truncatewords:"1" }}
{{ link1 }}
{{ link1|safe }}
{{ link }}
♠
{{ dot }}
{#add 可以加负数,传数字字符串都可以#}
{{ "10"|add:"-2" }}
{{ li.1|add:"-2" }}
{{ li.1|add:2 }}
{{ li.1|add:"2" }}
{{ li.1|add:"-2e" }}
{#upper#}
{{ name|upper }}
{{ 'LQZ'|lower }}
模版语法之标签
{#for 循环 循环列表,循环字典,循环列表对象#}
{% for foo in dic %}
{{ foo }}
{% endfor %}
{#也可以混用html标签#}
{% for foo in li %}
foo
{% endfor %}
{#表格#}
{% for foo in ll2 %}
{{ foo.name }}
{{ foo.age }}
{% endfor %}
{#'parentloop': {}, 'counter0': 0, 'counter': 1, 'revcounter': 4, 'revcounter0': 3, 'first': True, 'last': False}#}
{% for foo in ll2 %}
{{ forloop.counter }}
{{ foo.name }}
{{ foo.age }}
{% endfor %}
{% for foo in ll5 %}
foo.name
{% empty %}
空的
{% endfor %}
if判断
{% if name %}
hi {{ name }}
注销
{% else %}
请登录
注册
{% endif %}
{#还有elif#}
with
{% with ll2.0.name as n %}
{{ n }}
{% endwith %}
{{ n }}
{% load my_tag_filter %}
{{ 3|multi_filter:3 }}
{#传参必须用空格区分#}
{% multi_tag 3 9 10 %}
{#可以跟if连用#}
{% if 3|multi_filter:3 > 9 %}
大于
{% else %}
小于
{% endif %}
{{value|default:"nothing"}}
length:{{value|length}}
例如: 如果 value 是 ['a', 'b', 'c', 'd'],那么输出是 4。
filesizeformat:'13 KB'
, '4.1 MB'
, '102 bytes'
, 等等)
{{value|filesizeformat}}
例如: 如果 value
是 123456789,输出将会是 117.7 MB
。
date:{{ value|date:"Y-m-d" }} 2019-01-10
{{ value|date:"Y年m月d日" }} 2019年01月10日
slice:{{ value|slice:"2:-1" }} # lloworld
truncatechars:{{ value|truncatechars:9 }} #超过9个字符的字符串将以...显示
truncatewords:{{ value|truncatechars:2 }} #超过2个单词的字符串将以...显示 my name...
safe:value="点击"
{{value|safe}}
除了可以加过safe之后在视图层显示出来, 还可以在后台使用mark_safe()函数,在后台拼接出来的标签传进函数处理, 将得到的返回值传给模板层,再渲染到页面中,
其它过滤器(了解):{{ 224 | divisibleby:2 }} 返回 True
escape
按HTML转义,比如将”<”转换为”<”
filesizeformat
增加数字的可读性,转换结果为13KB,89MB,3Bytes等
{{ 1024 | filesizeformat }} 返回 1.0KB
first
返回列表的第1个元素,变量必须是一个列表
floatformat
转换为指定精度的小数,默认保留1位小数
{{ 3.1415926 | floatformat:3 }} 返回 3.142 四舍五入
get_digit
从个位数开始截取指定位置的数字
{{ 123456 | get_digit:’1’}}
join
用指定分隔符连接列表
{{ [‘abc’,’45’] | join:’*’ }} 返回 abc*45
length
返回列表中元素的个数或字符串长度
length_is
检查列表,字符串长度是否符合指定的值
{{ ‘hello’| length_is:’3’ }}
linebreaks
用或
标签包裹变量
{{ “Hi
David”|linebreaks }} 返回
Hi
David
linebreaksbr 用{{ 'asdikfjhihgie' | slice:':5' }} 返回 ‘asdik’
slugify
在字符串中留下减号和下划线,其它符号删除,空格用减号替换
{{ '5-2=3and5 2=3' | slugify }} 返回 5-23and5-23
stringformat
字符串格式化,语法同python
time
返回日期的时间部分
timesince
以“到现在为止过了多长时间”显示时间变量
结果可能为 45days, 3 hours
timeuntil
以“从现在开始到时间变量”还有多长时间显示时间变量
title
每个单词首字母大写
truncatewords
将字符串转换为省略表达方式
{{ 'This is a pen' | truncatewords:2 }}返回
This is ...
truncatewords_html
同上,但保留其中的HTML标签
{{ 'This is a pen
' | truncatewords:2 }}返回
This is ...
urlencode
将字符串中的特殊字符转换为url兼容表达方式
{{ ‘http://www.aaa.com/foo?a=b&b=c’ | urlencode}}
urlize
将变量字符串中的url由纯文本变为链接
wordcount
返回变量字符串中的单词数
yesno
将布尔变量转换为字符串yes, no 或maybe
{{ True | yesno }}
{{ False | yesno }}
{{ None | yesno }}
返回
yes
no
maybe
{% 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 person in person_list %}
{{ person.name }}
{% empty %}
sorry,no person here
{% endfor %}
{% if num > 100 or num < 0 %}
无效
{% elif num > 80 and num < 100 %}
优秀
{% else %}
凑活吧
{% endif %}
if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
不要写成as
第二种写法: 给复杂操作起别名
{% with business.employees.count as a %}
{{ a }} employee{{ total|pluralize }}
{% endwith %}
csrf_token
{% csrf_token%}
这个标签用于跨站请求伪造保护:
from django import template
from django.utils.safestring import mark_safe
register = template.Library() #register的名字是固定的,不可改变
@register.filter
def filter_multi(v1,v2):
return v1 * v2
@register.simple_tag
def simple_tag_multi(v1,v2):
return v1 * v2
@register.simple_tag
def my_input(id,arg):
result = "" %(id,arg,)
return mark_safe(result)
4、在使用自定义simple_tag和filter的html文件中导入之前创建的 my_tags.py
{% load my_tags %}
5、使用simple_tag和filter(如何调用)先使用load将定义好的过滤器或者标签加载出来
-------------------------------.html
{% load xxx %}
# num=12
{{ num|filter_multi:2 }} #24
{{ num|filter_multi:"[22,333,4444]" }}
{% simple_tag_multi 2 5 %} 参数不限,但不能放在if for语句中
{% simple_tag_multi num 5 %}
注意:filter可以用在if等语句后做判断条件,simple_tag不可以
{% if num|filter_multi:30 > 100 %}
{{ num|filter_multi:30 }}
{% endif %}
{% block title %}My amazing site{% endblock %}
{% block content %}{% endblock %}
这个模版,我们把它叫作 base.html(母版)
, 它定义了一个可以用于两列排版页面的简单HTML骨架。“子模版”的工作是用它们的内容填充空的blocks。
在这个例子中, block
标签定义了三个可以被子模版内容填充的block。 block
告诉模版引擎: 子模版可能会覆盖掉模版中的这些位置。
子模版可能看起来是这样的:
首先将模板继承过来
{% extends "base.html" %}
然后按照名字对各个block进行数据填充
{% block title %}My amazing blog{% endblock %}
{% block content %}
{% for entry in blog_entries %}
{{ entry.title }}
{{ entry.body }}
{% endfor %}
{% endblock %}
extends
标签是这里的关键。它告诉模版引擎,这个模版“继承”了另一个模版。当模版系统处理这个模版时,首先,它将定位父模版——在此例中,就是“base.html”。
那时,模版引擎将注意到 base.html
中的三个 block
标签,并用子模版中的内容来替换这些block。根据 blog_entries
的值,输出也就是填充好的子模板可能看起来是这样的:
My amazing blog
Entry one
This is my first entry.
Entry two
This is my second entry.
请注意,子模版并没有定义 sidebar
block,所以系统使用了父模版中的值。父模版的 {% block %}
标签中的内容总是被用作备选内容(fallback)。
这种方式使代码得到最大程度的复用,并且使得添加内容到共享的内容区域更加简单,例如,部分范围内的导航。
这里是使用继承的一些提示:
{% extends %}
标签,它必须是模版中的第一个标签。其他的任何情况下,模版继承都将无法工作。
{% block %}
标签越好,越多base模板的扩展性越好。请记住,子模版不必定义全部父模版中的blocks,所以,你可以在大多数blocks中填充合理的默认内容,然后,只定义你需要的那一个。多一点钩子总比少一点好。
{% block %}
中。
{% endblock %}
标签一个 名字 。例如:
{% block content %}
...
{% endblock content %}
在大型模版中,这个方法帮你清楚的看到哪一个 {% block %}
标签被关闭了。
block
标签。
# 首先加载定义static标签的文件
{% load static %}

引用JS文件时使用:
{% load static %}
某个文件多处被用到可以存为一个变量
{% load static %}
{% static "images/hi.jpg" as myphoto %}

{% load static %}

或者使用get_static_prefix取别名后再使用
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}

from django import template
register = template.Library()
@register.inclusion_tag('result.html')
def show_results(n):
n = 1 if n < 1 else int(n)
data = ["第{}项".format(i) for i in range(1, n+1)]
return {"data": data}
templates/snippets/result.html (这个就是html片段)
{% for choice in data %}
- {{ choice }}
{% endfor %}
templates/index.html (这个是目标html ,就是将html传入到该文件中的)
inclusion_tag test
{% load inclusion_tag_test %}
{% show_results 10 %}