Django模块笔记【四】

入门笔记翻译整理自:https://docs.djangoproject.com/en/1.8/topics/

*该笔记将对各个模块进行单独介绍

*template

1. 配置(Configuration)

 1 TEMPLATES = [
 2     {
 3         'BACKEND': 'django.template.backends.django.DjangoTemplates',
 4         'DIRS': [],
 5         'APP_DIRS': True,
 6         'OPTIONS': {
 7             # ... some options here ...
 8         },
 9     },
10 ]

 

2. 使用

get_template()载入模板,select_template()载入模板列表。他们会在DIRS指定的目录下寻找相应模板。

render_to_string()也载入模板,并立即调用相应的render()方法。


3. 自定义后台

 1 from django.template import TemplateDoesNotExist, TemplateSyntaxError
 2 from django.template.backends.base import BaseEngine
 3 from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
 4 
 5 import foobar
 6 
 7 
 8 class FooBar(BaseEngine):
 9 
10     # Name of the subdirectory containing the templates for this engine
11     # inside an installed application.
12     app_dirname = 'foobar'
13 
14     def __init__(self, params):
15         params = params.copy()
16         options = params.pop('OPTIONS').copy()
17         super(FooBar, self).__init__(params)
18 
19         self.engine = foobar.Engine(**options)
20 
21 
22     def from_string(self, template_code):
23         try:
24           return Template(self.engine.from_string(template_code))
25         except foobar.TemplateCompilationFailed as exc:
26             raise TemplateSyntaxError(exc.args)
27 
28     def get_template(self, template_name):
29         try:
30             return Template(self.engine.get_template(template_name))
31         except foobar.TemplateNotFound as exc:
32             raise TemplateDoesNotExist(exc.args)
33         except foobar.TemplateCompilationFailed as exc:
34             raise TemplateSyntaxError(exc.args)
35 
36 
37 class Template(object):
38 
39     def __init__(self, template):
40         self.template = template
41 
42     def render(self, context=None, request=None):
43         if context is None:
44             context = {}
45         if request is not None:
46             context['request'] = request
47             context['csrf_input'] = csrf_input_lazy(request)
48             context['csrf_token'] = csrf_token_lazy(request)
49         return self.template.render(context)

-- The End --

原文地址:https://www.cnblogs.com/py-drama/p/4624065.html