django-原理-django模板语言
django模板语言
详细语法:
https://docs.djangoproject.com/en/1.10/ref/templates/language/
django模板语言由四部分构成
Variables
在context为{'first_name': 'John', 'last_name': 'Doe'}时
My first name is {{ first_name }}. My last name is {{ last_name }}的结果是
My first name is John. My last name is Doe
目录查找、属性查找、list索引都是点号分隔的
如果变量可以使用,模板直接替换变量内容
Tags
tag被 {%和%}包围
像
{% csrf_token %}
大部分tag可接收参数
{% cycle 'odd' 'even' %}
有些tag需要开始和结束tag
{% if user.is_authenticated %}Hello, {{ user.username }}.{% endif %}
内置tag参考:
https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#ref-templates-builtins-tags
定制tag:
https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-tags
Filters
filter转换变量的值,像这样
{{ django|title }}
如果上下文是:{'django': 'the web framework for perfectionists with deadlines'}
这个模板被渲染为
The Web Framework For Perfectionists With Deadlines
一些filter可以传参
{{ my_date|date:"Y-m-d" }}
内置的filter参考:
https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#ref-templates-builtins-filters
定制filter:
https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#howto-writing-custom-template-filters
Comments
注释
{# this won't be rendered #}
{% comment %} tag可以提供多行注释
api组件
关于django模板语言的api,可以参考
https://docs.djangoproject.com/en/1.10/ref/templates/api/
组件包括五个部分
Engine
Template
Context
Loaders
Context processors
engine
django.template.Engine是django的模板系统,能够在django项目外独立使用;
django.template.backends.django.DjangoTemplates封装了django.template.Engine,并且能够适配django的模板api
Template
django.template.Template代表了一个可渲染的模板,模板通过Engine.get_template()或者Engine.from_string()获得
同样的django.template.backends.django.Template封装了django.template.Template,适配到通用的模板api
Context
django.template.Context除了context,还保存了一些元数据,传递到Template.render()用来渲染模板
django.template.RequestContext是context的子类,保存了当前的HttpRequest并且云心模板context processor
通用api没有类似的概念,Context数据通过简单的dict传递 HttpRequest也是按需传递
Loaders
用来定位、加载、并返回Template对象
内置的loaders:
https://docs.djangoproject.com/en/1.10/ref/templates/api/#template-loaders
定制loader:
https://docs.djangoproject.com/en/1.10/ref/templates/api/#custom-template-loaders
Context processors
上线文处理器,用来接收当前的HttpRequest,并返回dict
在全部的模板中构造共享的数据
内置的context processors
https://docs.djangoproject.com/en/1.10/ref/templates/api/#context-processors
 
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号