Python学习之路—2018/6/20

Python学习之路—2018/6/20

1.模板语法之变量

views.py

def index(request):
    import datetime
    s="gyq"
    l=[1,2,3]    
    dic={"name":"gyq","age":22}  
    date = datetime.date(1996, 5, 27)   # 
    class Person(object):
        def __init__(self,name):
            self.name=name
    person_yuan=Person("gyq")  
    return render(request,"index.html",locals()) 
	'''相当于 return render(request,"index.html{"l":l,"dic":dic,"date":date,"person_list":person_list}) 	'''

template

<h4>{{s}}</h4>
<h4>列表:{{ l.0 }}</h4>
<h4>字典:{{ dic.name }}</h4>
<h4>日期:{{ date.year }}</h4>
<h4>类对象列表:{{ person_list.0.name }}</h4>

2.模板语法之过滤器

default

如果一个变量是false或者为空,使用给定的默认值。否则,使用变量的值

>>> l = []
>>> <p>{{ l|default:"nothing" }}</p>

length

返回值的长度。

>>> dic = {"name": "gyq", "age": 22}
>>> <p>{{ dic|length }}</p>

filesizeformat

将值格式化为文件大小

>>> value = 123456
>>> <p>{{ value|filesizeformat }}</p>

date

将时间戳转化成自定义格式

>>> date = datetime.datetime.now()
>>> <p>{{ date|date:"Y-m-d" }}</p>

slice

切片

>>> s = "gyq1314"
>>> <p>{{ s|slice:"0:3" }}</p>

truncatechars

如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“...”)结尾。

>>> content = "上世纪90年代末,在IT公司任职的张长弓凭借出色的专业能力在互联网商业领域初尝成功滋味。"
>>> <p>{{ content|truncatechars:10 }}</p>

safe

当被渲染的含有标签时,Django会自动转义,这时需要使用safe过滤器

>>> a = "<a href='#'>click</a>"
>>> <p>{{ a|safe }}</p>

3.模板语法之标签

for标签

遍历每一个元素

{% for person in person_list %}
    <p>{{ person.name }}</p>
{% endfor %}
{% for person in person_list %}
    <p>{{ person.name },{ person.age }}</p>
{% endfor %}

遍历字典

{% for key,val in dic.items %}
    <p>{{ key }}:{{ val }}</p>
{% endfor %}

循环序号

{% for key,val in dic.items %}
    <p>{{ forloop.counter }}{{ key }}:{{ val }}</p>
{% endfor %}
forloop.counter            序号从1开始
forloop.counter0           序号从0开始
forloop.revcounter         反向循环,序号从1开始
forloop.revcounter0        反向循环,序号从0开始
forloop.first              如果当前是第一次循环则返回True
forloop.last               如果当前是最后一次循环则返回True

for...empty标签

在给出的组是空的或者没有被找到时,进行的操作

{% for person in person_list %}
    <p>{{ person.name }}</p>
{% empty %}
    <p>nothing</p>
{% endfor %}

if标签

{% if a > 100 or a < 0 %}
    <p>错误</p>
{% elif a > 90 and a < 100 %}
    <p>优秀</p>
{% elif a > 80 and a < 90 %}
    <p>良好</p>
{% elif a > 70 and a < 80 %}
    <p>中等</p>
{% elif a > 60 and a < 70 %}
    <p>及格</p>
{% else %}
    <p>不及格</p>
{% endif %}

with标签

当变量名字较为复杂时,使用此标签缓存一个简单的名字

{% with person_list.1.name as name %}
    {{ name }}
{% endwith %}
原文地址:https://www.cnblogs.com/ExBurner/p/9206410.html