{{ }}
{# 取variable中的第一个参数 #} {{ variable.0 }} {# 取字典dic中key的值 #} {{ dic.key }} {# 取obj_list对象列表中第一个对象的attr属性值 #} {{ obj_list.0.attr }} {# 点操做只能调用不带参数的方法 #} {{ obj_list.0.method }}
{% %}
forhtml
{% for item in item_list %}...{% empty %}...{% endfor %}
经常使用for循环参数:python
Variable | Description |
---|---|
forloop.counter |
当前循环的索引值(从1开始) |
forloop.counter0 |
当前循环的索引值(从0开始) |
forloop.revcounter |
当前循环的倒序索引值(从1开始) |
forloop.revcounter0 |
当前循环的倒序索引值(从0开始) |
forloop.first |
当前循环是否是第一次循环(布尔值) |
forloop.last |
当前循环是否是最后一次循环(布尔值) |
forloop.parentloop |
本层循环的外层循环 |
ifdjango
{% if some_condition %}...{% elif other_condition %}...{% endif %}
and 、or、==、>、<、!=、<=、>=、in、not in、is、is not
with安全
{% with new_variable = old_variable %}.....{% endwith %}
csrf_tokenapp
{% csrf_token %}
注释ide
{# note #}
继承oop
{% extends 'base.html' %}
块 blockui
{% block block_name %}...{% endblock %}
组件spa
{% include 'subassembly.html' %}
引用静态文件目录翻译
{% load static %}
{% load static %}
<img src="{% static 'images/sample.jpg' %}"></img>
引用静态文件目录
{% load static %}
<img src="{% get_static_prefix %}images/sample.jpg"></img>
自定义simpletag的步骤(与自定义Filter相似,不过接收更灵活的参数)
custom_simpletag.py中编写自定义simpletag,例如:
from django import template register = template.Library() @register.simple_tag(name="my_simpletag") def add_simpletag(a,b,c): # 可接收多个参数 return "{} + {} + {}".format(a, b, c)
{% load custom_simpletag %} {% my_simpletag "1" "2" "3" %}
自定义inclusion_tag的步骤
custom_inclusiontag.py中编写自定义inclusiontag,例如:
from django import template register = template.Library() @register.inclusion_tag('inclusion_tag.html') def my_inclusiontag(n): n = 1 if n < 1 else int(n) data = ["第{}项".format(i) for i in range(1, n+1)] return {"data": data}
在templates文件夹中建立刚才注册的inclusion_tag.html文件
<ul> {% for choice in data %} <li>{{ choice }}</li> {% endfor %} </ul>
使用自定义my_inclusiontag前,首先在HTML页面中导入py文件
{% load custom_inclusiontag %} {% my_inclusiontag 10 %}
语法:{{ value|filter_name:args }}
,注意:管道符先后没有空格
default
{{ value: default: "自定义内容"}}
length
filesizeformat
{{ value|filesizeformat }}
slice
{{value|slice:"start:end"}}
date
{{ value|date:"Y-m-d H: i:s"}}
safe
{{value|safe}}
truncatechars
自定义过滤器的步骤
在custom_filter.py中编写自定义过滤器,例如:
from django import template register = template.Library() @register.filter(name="my_filter") def my_filter(value, arg): #最多接收两个参数 return value.replace(arg, "")
{% load custom_filter %} {{ variable|my_filter:"0" }}
官方连接
https://docs.djangoproject.com/en/1.11/ref/templates/language/
官方连接-内置标签
https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#built-in-tag-reference
官方连接-内置过滤器
https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#built-in-filter-reference
其余连接
http://baijiahao.baidu.com/s?id=1578789736945590676&wfr=spider&for=pc
https://code.ziqiangxuetang.com/django/django-template2.html