1.创建环境
(python37_django2) D:pythondjango_imooc_xiaobai>django-admin startproject jinja (python37_django2) D:pythondjango_imooc_xiaobai>pip install jinja2 (python37_django2) D:pythondjango_imooc_xiaobai>cd jinja (python37_django2) D:pythondjango_imooc_xiaobaijinja>python manage.py startapp app
2.创建jinja2的基础环境文件
app/base_jinja2.py
# _*_ coding:utf-8 _*_ # __author__ == 'jack' # __date__ == '2020-12-31 10:13 AM' from jinja2 import Environment from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import reverse from .myfilter import test def environment(**options): env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse }) # 自定义过滤器 env.filters['test'] = test return env
3.配置django
注册app
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', ]
模板配置
TEMPLATES = [ { # 修改默认的template为 jinja2 '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', ], 'environment': 'app.base_jinja2.environment' }, }, ]
加入路由
jinja2/urls.py
from django.contrib import admin from django.urls import path from app.views import test urlpatterns = [ path('admin/', admin.site.urls), path('test/', test) ]
4.创建模板文件
templates/base.html
<!DOCTYPE html> <html lang="en"> <head> {% block head %} <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> {% block css_style %} {% endblock %} {% endblock %} </head> <body> {% block content %} {% endblock %} {% block js_script %} {% endblock %} </body> </html>
测试文件
templates/test.html
{% extends 'base.html' %} {% block css_style %} <link rel="stylesheet" href="/static/test.css"> {% endblock %} {% block content %} {{ name|title }},{{ age }}<br/> {{ age|test(2) }}<br/> {% endblock %}
5.视图
app/views.py
from django.shortcuts import render # Create your views here. def test(request): data = {'name': 'jack', 'age': 18} return render(request, 'test.html', data)