第六章——深入模板
自定义模板标签和自定义过滤器
from django import template
register = template.Library()
class ReversalNode(template.Node):
def __init__(self, value):
self.value = str(value)
def render(self, context):
return self.value[::-1]
@register.tag(name='reversal')
def do_reversal(parse, token):
try:
tag_name, value = token.split_contents()
except:
raise template.TemplateSyntaxError('syntax')
return ReversalNode(value)
@register.filter(name='replace')
def do_replace(value, args):
oldvalue = args.split(':')[0]
newvalue = args.split(':')[1]
return value.replace(oldvalue, newvalue)
<!DOCTYPE html>
{% load custom_tags %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% reversal 'Django' %}
{{ value | replace:'Python:Django' }}
</body>
</html>
Jinja2模板引擎
pip3 install Jinja2
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse
from jinja2 import Environment
def environment(**option):
env = Environment(**option)
env.globals.update({
'static': staticfiles_storage.url,
'url': reverse,
})
return env
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [BASE_DIR, 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'environment': 'web_test.jinja2_tem.environment',
},
},
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
jinja 自定义过滤器
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse
from jinja2 import Environment
def myreplace(value, old='jinja2', new='django'):
return str(value).replace(old, new)
def environment(**option):
env = Environment(**option)
env.globals.update({
'static': staticfiles_storage.url,
'url': reverse,
})
env.filters['myreplace'] = myreplace
return env