Django Template 进阶
回顾:
Variables
{{ var }} {{ dict.key }} {{ var.attr }} {{ var.method }} {{ varindex }}
Filter
{{ list | join."," }} {{ name | lower }}
Tags
{% tag xxx % } xxx {% endtag %} {% for ... %} xxx {% endfor %}
{# comment #}
配置Template引擎
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 'BACKEND': 'django.template.backends.jinja2.Jinja2, 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
获取和渲染模板
-
django.template.loader.get_template(template_name,using=None)
-
django.shortcuts.render()
-
Template.render(content=None,request=None)
-
django.template.loader.render_to_string(template_name, context=None, request=None, using=None)
其中 'APP_DIRS': True 可以向app目录下寻找模板
Context processors
Context processors 可以向HttpRequest中注入一些全局性参数
- django.contrib.auth.context_processors.auth
user
perms
- django.template.context_processors.debug
debug
sql_query
- django.template.context_processors.media
MEDIA_URL
自定义processors
1. 项目目录下新增 context_processors.py
自定义函数,第一个参数必须为 HttpRequest object,返回一个字典
def global_setting(request): user = { 'name': 'alex', 'age': 18, 'sex': 'male' } return user
2. OPTIONS 添加路径
3. 前端展示
<h2>自定义context_processors</h2> {{ name }}<br/> {{ age }}<br/> {{ sex }}<br/>
内置Template Tag 和 Filters
https://docs.djangoproject.com/en/1.11/ref/templates/builtins/
自定义Template Filter
Django寻找自定义filter的目录是 app_name/templatetags
新建文件 mytags.py
from django import template register = template.Library() @register.filter def lower(text): return text.lower() @register.filter def question_choice_count(question): return question.choice_set.count() @register.filter def question_choice_count_add(question, num): return question.choice_set.count() + int(num)
前端使用,重启服务,加载标签
{% load static %} {% load mytags %} <body> <img src="{% static 'django.png' %}"> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:vote' question.id %}">{{ question.question_text }}</a> -- {{ question | question_choice_count }} -- {{ question| question_choice_count_add:2 }} </li> {% endfor %} </ul> {% endif %} </body>
模板扩展和包含
扩展 extends,是在继承模板,然后自定义可以设置block
包含 include,是导入一个模板片段到该位置
# mysite/templates/base.html <html> <head> <title> {% block title %} {% endblock %}</title> {% include '_head_css_js.html' %} </head> <body> {% include '_header.html' %} {% block content %} {% endblock %} {% include '_footer.html' %} </body> </html> # mysite/templates/_header.html <div> This is header </div> # mysite/templates/_footer.html <div> This is footer </div> # mysite/templates/_head_css_js.html # mysite/templates/index.html {% extends 'base.html' %} {% block content %} <h1> Index 1 </h1> {% endblock %}
posted on 2017-09-08 17:38 Jonathan1314 阅读(259) 评论(0) 编辑 收藏 举报