class PostOfficeTemplates(BaseEngine): """ Customized Template Engine which keeps track on referenced images and stores them as attachments to be used in multipart email messages. """ app_dirname = 'templates' def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() options.setdefault('autoescape', True) options.setdefault('debug', settings.DEBUG) options.setdefault('file_charset', settings.FILE_CHARSET) libraries = options.get('libraries', {}) options['libraries'] = self.get_templatetag_libraries(libraries) super(PostOfficeTemplates, self).__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options) def from_string(self, template_code): return Template(self.engine.from_string(template_code), self) def get_template(self, template_name): try: template = self.engine.get_template(template_name) return Template(template, self) except TemplateDoesNotExist as exc: reraise(exc, self) def get_templatetag_libraries(self, custom_libraries): libraries = get_installed_libraries() libraries.update(custom_libraries) return libraries
def test_polygons_templates(self): # Accessing Polygon attributes in templates should work. engine = Engine() template = engine.from_string('{{ polygons.0.wkt }}') polygons = [fromstr(p.wkt) for p in self.geometries.multipolygons[:2]] content = template.render(Context({'polygons': polygons})) self.assertIn('MULTIPOLYGON (((100', content)
class DjangoTemplates(BaseEngine): app_dirname = 'templates' def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() options.setdefault('autoescape', True) options.setdefault('debug', settings.DEBUG) options.setdefault('file_charset', settings.FILE_CHARSET) libraries = options.get('libraries', {}) options['libraries'] = self.get_templatetag_libraries(libraries) super().__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options) def from_string(self, template_code): return Template(self.engine.from_string(template_code), self) def get_template(self, template_name): try: return Template(self.engine.get_template(template_name), self) except TemplateDoesNotExist as exc: reraise(exc, self) def get_templatetag_libraries(self, custom_libraries): """ Return a collation of template tag libraries from installed applications and the supplied custom_libraries argument. """ libraries = get_installed_libraries() libraries.update(custom_libraries) return libraries
def test_loader_priority(self): """ #21460 -- Check that the order of template loader works. """ loaders = ["django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader"] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template("priority/foo.html") self.assertEqual(template.render(Context()), "priority\n")
def test_loader_priority(self): """ #21460 -- The order of template loader works. """ loaders = [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n')
def test_loaders_security(self): ad_loader = app_directories.Loader(Engine.get_default()) fs_loader = filesystem.Loader(Engine.get_default()) def test_template_sources(path, template_dirs, expected_sources): if isinstance(expected_sources, list): # Fix expected sources so they are abspathed expected_sources = [os.path.abspath(s) for s in expected_sources] # Test the two loaders (app_directores and filesystem). func1 = lambda p, t: list(ad_loader.get_template_sources(p, t)) func2 = lambda p, t: list(fs_loader.get_template_sources(p, t)) for func in (func1, func2): if isinstance(expected_sources, list): self.assertEqual(func(path, template_dirs), expected_sources) else: self.assertRaises(expected_sources, func, path, template_dirs) template_dirs = ['/dir1', '/dir2'] test_template_sources('index.html', template_dirs, ['/dir1/index.html', '/dir2/index.html']) test_template_sources('/etc/passwd', template_dirs, []) test_template_sources('etc/passwd', template_dirs, ['/dir1/etc/passwd', '/dir2/etc/passwd']) test_template_sources('../etc/passwd', template_dirs, []) test_template_sources('../../../etc/passwd', template_dirs, []) test_template_sources('/dir1/index.html', template_dirs, ['/dir1/index.html']) test_template_sources('../dir2/index.html', template_dirs, ['/dir2/index.html']) test_template_sources('/dir1blah', template_dirs, []) test_template_sources('../dir1blah', template_dirs, []) # UTF-8 bytestrings are permitted. test_template_sources(b'\xc3\x85ngstr\xc3\xb6m', template_dirs, ['/dir1/Ångström', '/dir2/Ångström']) # Unicode strings are permitted. test_template_sources('Ångström', template_dirs, ['/dir1/Ångström', '/dir2/Ångström']) test_template_sources('Ångström', [b'/Stra\xc3\x9fe'], ['/Straße/Ångström']) test_template_sources(b'\xc3\x85ngstr\xc3\xb6m', [b'/Stra\xc3\x9fe'], ['/Straße/Ångström']) # Invalid UTF-8 encoding in bytestrings is not. Should raise a # semi-useful error message. test_template_sources(b'\xc3\xc3', template_dirs, UnicodeDecodeError) # Case insensitive tests (for win32). Not run unless we're on # a case insensitive operating system. if os.path.normcase('/TEST') == os.path.normpath('/test'): template_dirs = ['/dir1', '/DIR2'] test_template_sources('index.html', template_dirs, ['/dir1/index.html', '/DIR2/index.html']) test_template_sources('/DIR1/index.HTML', template_dirs, ['/DIR1/index.HTML'])
class AppDirectoriesLoaderTest(SimpleTestCase): def setUp(self): self.engine = Engine( loaders=['django.template.loaders.app_directories.Loader'], ) @override_settings(INSTALLED_APPS=['template_tests']) def test_load_template(self): self.engine.get_template('index.html') @override_settings(INSTALLED_APPS=[]) def test_not_installed(self): with self.assertRaises(TemplateDoesNotExist): self.engine.get_template('index.html')
def setUp(self): self.loader = eggs.Loader(Engine.get_default()) # Defined here b/c at module scope we may not have pkg_resources class MockProvider(pkg_resources.NullProvider): def __init__(self, module): pkg_resources.NullProvider.__init__(self, module) self.module = module def _has(self, path): return path in self.module._resources def _isdir(self, path): return False def get_resource_stream(self, manager, resource_name): return self.module._resources[resource_name] def _get(self, path): return self.module._resources[path].read() def _fn(self, base, resource_name): return os.path.normcase(resource_name) pkg_resources._provider_factories[MockLoader] = MockProvider self.empty_egg = create_egg("egg_empty", {}) self.egg_1 = create_egg("egg_1", { os.path.normcase('templates/y.html'): StringIO("y"), os.path.normcase('templates/x.txt'): StringIO("x"), })
def get_context_data(self, **kwargs): template = self.kwargs['template'] templates = [] try: default_engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = os.path.join(directory, template) templates.append({ 'file': template_file, 'exists': os.path.exists(template_file), 'contents': lambda: open(template_file).read() if os.path.exists(template_file) else '', 'order': index, }) kwargs.update({ 'name': template, 'templates': templates, }) return super(TemplateDetailView, self).get_context_data(**kwargs)
class SSITests(SimpleTestCase): def setUp(self): self.this_dir = os.path.dirname(os.path.abspath(upath(__file__))) self.ssi_dir = os.path.join(self.this_dir, "templates", "first") self.engine = Engine(allowed_include_roots=(self.ssi_dir, )) def render_ssi(self, path): # the path must exist for the test to be reliable self.assertTrue(os.path.exists(path)) return self.engine.from_string('{%% ssi "%s" %%}' % path).render( Context({})) def test_allowed_paths(self): acceptable_path = os.path.join(self.ssi_dir, "..", "first", "test.html") self.assertEqual(self.render_ssi(acceptable_path), 'First template\n') def test_relative_include_exploit(self): """ May not bypass allowed_include_roots with relative paths e.g. if allowed_include_roots = ("/var/www",), it should not be possible to do {% ssi "/var/www/../../etc/passwd" %} """ disallowed_paths = [ os.path.join(self.ssi_dir, "..", "ssi_include.html"), os.path.join(self.ssi_dir, "..", "second", "test.html"), ] for disallowed_path in disallowed_paths: self.assertEqual(self.render_ssi(disallowed_path), '')
def get_context_data(self, **kwargs): filters = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [('', lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for filter_name, filter_func in library.filters.items(): title, body, metadata = utils.parse_docstring( filter_func.__doc__) if title: title = utils.parse_rst(title, 'filter', _('filter:') + filter_name) if body: body = utils.parse_rst(body, 'filter', _('filter:') + filter_name) for key in metadata: metadata[key] = utils.parse_rst( metadata[key], 'filter', _('filter:') + filter_name) tag_library = module_name.split('.')[-1] filters.append({ 'name': filter_name, 'title': title, 'body': body, 'meta': metadata, 'library': tag_library, }) kwargs.update({'filters': filters}) return super(TemplateFilterIndexView, self).get_context_data(**kwargs)
def get_context_data(self, **kwargs): template = self.kwargs['template'] templates = [] try: default_engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(directory) / template if template_file.exists(): template_contents = template_file.read_text() else: template_contents = '' templates.append({ 'file': template_file, 'exists': template_file.exists(), 'contents': template_contents, 'order': index, }) return super().get_context_data(**{ **kwargs, 'name': template, 'templates': templates, })
def get_context_data(self, **kwargs): tags = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [('', lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for tag_name, tag_func in library.tags.items(): title, body, metadata = utils.parse_docstring( tag_func.__doc__) title = title and utils.parse_rst(title, 'tag', _('tag:') + tag_name) body = body and utils.parse_rst(body, 'tag', _('tag:') + tag_name) for key in metadata: metadata[key] = utils.parse_rst( metadata[key], 'tag', _('tag:') + tag_name) tag_library = module_name.split('.')[-1] tags.append({ 'name': tag_name, 'title': title, 'body': body, 'meta': metadata, 'library': tag_library, }) return super().get_context_data(**{**kwargs, 'tags': tags})
def create_index_file_from_template(mode, commit): if mode == "prod": options = { "DIST_DIR": "/dist-{}/min".format(commit), "VENDOR_CSS_PREFIX": "vendor-min", "APP_CSS_PREFIX": "app-min", "VENDOR_JS_PREFIX": "vendor-min", "APP_JS_PREFIX": "app-min", "INDEX_FILE_NAME": "prod-index.html", "COMMIT": "-{}".format(commit) } elif mode == "dev": options = { "DIST_DIR": "/dist", "VENDOR_CSS_PREFIX": "vendor", "APP_CSS_PREFIX": "app", "VENDOR_JS_PREFIX": "vendor", "APP_JS_PREFIX": "app", "INDEX_FILE_NAME": "index.html", "COMMIT": "" } else: raise Exception("Invalid OPS_MODE, {} found".format(mode)) with open("./index-template.html", "r") as f: template_string = f.read() template = Template(template_string, engine=Engine()) context = Context(options) output_string = template.render(context) with open(options['INDEX_FILE_NAME'], 'w') as f: f.write(output_string)
def check_dependencies(self): """ Check that all things needed to run the admin have been correctly installed. The default implementation checks that admin and contenttypes apps are installed, as well as the auth context processor. """ if not apps.is_installed('django.contrib.admin'): raise ImproperlyConfigured( "Put 'django.contrib.admin' in your INSTALLED_APPS " "setting in order to use the admin application.") if not apps.is_installed('django.contrib.contenttypes'): raise ImproperlyConfigured( "Put 'django.contrib.contenttypes' in your INSTALLED_APPS " "setting in order to use the admin application.") try: default_template_engine = Engine.get_default() except Exception: # Skip this non-critical check: # 1. if the user has a non-trivial TEMPLATES setting and Django # can't find a default template engine # 2. if anything goes wrong while loading template engines, in # order to avoid raising an exception from a confusing location # Catching ImproperlyConfigured suffices for 1. but 2. requires # catching all exceptions. pass else: if ('django.contrib.auth.context_processors.auth' not in default_template_engine.context_processors): raise ImproperlyConfigured( "Enable 'django.contrib.auth.context_processors.auth' " "in your TEMPLATES setting in order to use the admin " "application.")
def get_context_data(self, **kwargs): template = self.kwargs["template"] templates = [] try: default_engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(safe_join(directory, template)) if template_file.exists(): template_contents = template_file.read_text() else: template_contents = "" templates.append( { "file": template_file, "exists": template_file.exists(), "contents": template_contents, "order": index, } ) return super().get_context_data( **{ **kwargs, "name": template, "templates": templates, } )
def get_context_data(self, **kwargs): filters = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [("", lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for filter_name, filter_func in library.filters.items(): title, body, metadata = utils.parse_docstring(filter_func.__doc__) title = title and utils.parse_rst( title, "filter", _("filter:") + filter_name ) body = body and utils.parse_rst( body, "filter", _("filter:") + filter_name ) for key in metadata: metadata[key] = utils.parse_rst( metadata[key], "filter", _("filter:") + filter_name ) tag_library = module_name.split(".")[-1] filters.append( { "name": filter_name, "title": title, "body": body, "meta": metadata, "library": tag_library, } ) return super().get_context_data(**{**kwargs, "filters": filters})
def setUpClass(cls): cls.engine = Engine( loaders=[('django.template.loaders.locmem.Loader', { 'index.html': 'index', })], ) super(LocmemLoaderTests, cls).setUpClass()
def _handler(self, request, *args, **kwargs): # Rethinking of this logic in 5 years, aka, working around RequestContext that doesn't seem to actually work context = {} for processor in Engine.get_default().context_processors: context.update(import_string(processor)(self.request)) if context['page'] and context['exact_match']: if context['page'].redirect_url: if context['page'].redirect_permanent: return HttpResponsePermanentRedirect(context['page'].redirect_url) else: return HttpResponseRedirect(context['page'].redirect_url) if context['page'].view: if context['page'].view.find('.as_view(') != -1: pass else: cls = get_callable(context['page'].view) return cls(request) if context['page'].template: self.template_name = context['page'].template elif context['page'].inherit_template: for i in context['pageA']: if i.template: self.template_name = i.template content = loader.render_to_string(self.template_name, context) return HttpResponse(content) raise Http404
def patch_builtins(library): if django.VERSION < (1, 9): return patch('django.template.base.builtins', [library]) else: from django.template.engine import Engine engine = Engine.get_default() return patch.object(engine, 'template_builtins', [library])
def get_context_data(self, **kwargs): template = self.kwargs['template'] templates = [] try: default_engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = os.path.join(directory, template) if os.path.exists(template_file): with open(template_file) as f: template_contents = f.read() else: template_contents = '' templates.append({ 'file': template_file, 'exists': os.path.exists(template_file), 'contents': template_contents, 'order': index, }) kwargs.update({ 'name': template, 'templates': templates, }) return super().get_context_data(**kwargs)
def get_context_data(self, **kwargs): template = self.kwargs['template'] templates = [] for dir in Engine.get_default().dirs: template_file = os.path.join(dir, template) templates.append({ 'file': template_file, 'exists': os.path.exists(template_file), 'contents': lambda: open(template_file).read() if os.path.exists(template_file) else '', 'order': list(Engine.get_default().dirs).index(dir), }) kwargs.update({ 'name': template, 'templates': templates, }) return super(TemplateDetailView, self).get_context_data(**kwargs)
def check_dependencies(self): """ Check that all things needed to run the admin have been correctly installed. The default implementation checks that admin and contenttypes apps are installed, as well as the auth context processor. """ if not apps.is_installed('django.contrib.admin'): raise ImproperlyConfigured( "Put 'django.contrib.admin' in your INSTALLED_APPS " "setting in order to use the admin application.") if not apps.is_installed('django.contrib.contenttypes'): raise ImproperlyConfigured( "Put 'django.contrib.contenttypes' in your INSTALLED_APPS " "setting in order to use the admin application.") try: default_template_engine = Engine.get_default() except ImproperlyConfigured: # Skip the check if the user has a non-trivial TEMPLATES setting pass else: if ('django.contrib.auth.context_processors.auth' not in default_template_engine.context_processors): raise ImproperlyConfigured( "Enable 'django.contrib.auth.context_processors.auth' " "in your TEMPLATES setting in order to use the admin " "application.")
def setUp(self): self.loader = eggs.Loader(Engine.get_default()) # Defined here b/c at module scope we may not have pkg_resources class MockProvider(pkg_resources.NullProvider): def __init__(self, module): pkg_resources.NullProvider.__init__(self, module) self.module = module def _has(self, path): return path in self.module._resources def _isdir(self, path): return False def get_resource_stream(self, manager, resource_name): return self.module._resources[resource_name] def _get(self, path): return self.module._resources[path].read() def _fn(self, base, resource_name): return os.path.normcase(resource_name) pkg_resources._provider_factories[MockLoader] = MockProvider self.empty_egg = create_egg("egg_empty", {}) self.egg_1 = create_egg( "egg_1", { os.path.normcase('templates/y.html'): StringIO("y"), os.path.normcase('templates/x.txt'): StringIO("x"), })
def template_source(request): """ Return the source of a template, syntax-highlighted by Pygments if it's available. """ template_origin_name = request.GET.get('template_origin', None) if template_origin_name is None: return HttpResponseBadRequest('"template_origin" key is required') try: template_origin_name = signing.loads(template_origin_name) except Exception: return HttpResponseBadRequest('"template_origin" is invalid') template_name = request.GET.get('template', template_origin_name) final_loaders = [] loaders = Engine.get_default().template_loaders for loader in loaders: if loader is not None: # When the loader has loaders associated with it, # append those loaders to the list. This occurs with # django.template.loaders.cached.Loader if hasattr(loader, 'loaders'): final_loaders += loader.loaders else: final_loaders.append(loader) for loader in final_loaders: if Origin: # django>=1.9 origin = Origin(template_origin_name) try: source = loader.get_contents(origin) break except TemplateDoesNotExist: pass else: # django<1.9 try: source, _ = loader.load_template_source(template_name) break except TemplateDoesNotExist: pass else: source = "Template Does Not Exist: %s" % (template_origin_name,) try: from pygments import highlight from pygments.lexers import HtmlDjangoLexer from pygments.formatters import HtmlFormatter source = highlight(source, HtmlDjangoLexer(), HtmlFormatter()) source = mark_safe(source) source.pygmentized = True except ImportError: pass # Using SimpleTemplateResponse avoids running global context processors. return SimpleTemplateResponse('debug_toolbar/panels/template_source.html', { 'source': source, 'template_name': template_name })
class SSITests(SimpleTestCase): def setUp(self): self.this_dir = os.path.dirname(os.path.abspath(upath(__file__))) self.ssi_dir = os.path.join(self.this_dir, "templates", "first") self.engine = Engine(allowed_include_roots=(self.ssi_dir,)) def render_ssi(self, path): # the path must exist for the test to be reliable self.assertTrue(os.path.exists(path)) return self.engine.from_string('{%% ssi "%s" %%}' % path).render(Context({})) def test_allowed_paths(self): acceptable_path = os.path.join(self.ssi_dir, "..", "first", "test.html") self.assertEqual(self.render_ssi(acceptable_path), 'First template\n') def test_relative_include_exploit(self): """ May not bypass allowed_include_roots with relative paths e.g. if allowed_include_roots = ("/var/www",), it should not be possible to do {% ssi "/var/www/../../etc/passwd" %} """ disallowed_paths = [ os.path.join(self.ssi_dir, "..", "ssi_include.html"), os.path.join(self.ssi_dir, "..", "second", "test.html"), ] for disallowed_path in disallowed_paths: self.assertEqual(self.render_ssi(disallowed_path), '')
def get_context_data(self, **kwargs): filters = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [('', lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for filter_name, filter_func in library.filters.items(): title, body, metadata = utils.parse_docstring(filter_func.__doc__) if title: title = utils.parse_rst(title, 'filter', _('filter:') + filter_name) if body: body = utils.parse_rst(body, 'filter', _('filter:') + filter_name) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], 'filter', _('filter:') + filter_name) tag_library = module_name.split('.')[-1] filters.append({ 'name': filter_name, 'title': title, 'body': body, 'meta': metadata, 'library': tag_library, }) kwargs.update({'filters': filters}) return super().get_context_data(**kwargs)
def get_context_data(self, **kwargs): filters = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES secure aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [("", lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for filter_name, filter_func in library.filters.items(): title, body, metadata = utils.parse_docstring(filter_func.__doc__) if title: title = utils.parse_rst(title, "filter", _("filter:") + filter_name) if body: body = utils.parse_rst(body, "filter", _("filter:") + filter_name) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], "filter", _("filter:") + filter_name) tag_library = module_name.split(".")[-1] filters.append( {"name": filter_name, "title": title, "body": body, "meta": metadata, "library": tag_library} ) kwargs.update({"filters": filters}) return super(TemplateFilterIndexView, self).get_context_data(**kwargs)
def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() options.setdefault('debug', settings.TEMPLATE_DEBUG) options.setdefault('file_charset', settings.FILE_CHARSET) super(DjangoTemplates, self).__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options)
def send_notification(books: list): """ Send email via SendGrid :param books: book list :return: True/False """ # Read template file with open('Template.html', 'r') as file: data = file.read() # Using Django template create email content settings.configure(DEBUG=False) template = Template(data, engine=Engine()) context = Context({'books': books}) output = template.render(context) message = Mail(from_email=config('FROM_EMAIL'), to_emails=config('TO_EMAIL'), subject='Audiobooks Newsletter (AudiobookBay)', html_content=output) try: sg = SendGridAPIClient(config('SENDGRID_API_KEY')) response = sg.send(message) if response.status_code != 202: # Cannot send email return False except: return False return True
class DjangoTemplates(BaseEngine): app_dirname = 'templates' def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() options.setdefault('autoescape', True) options.setdefault('debug', settings.DEBUG) options.setdefault('file_charset', 'utf-8') libraries = options.get('libraries', {}) # 下面这个值是字典对象 # {'cache': 'django.templatetags.cache', # 'i18n': 'django.templatetags.i18n', # 'l10n': 'django.templatetags.l10n', # 'static': 'django.templatetags.static', # 'tz': 'django.templatetags.tz', # 'admin_list': 'django.contrib.admin.templatetags.admin_list', # 'admin_modify': 'django.contrib.admin.templatetags.admin_modify', # 'admin_urls': 'django.contrib.admin.templatetags.admin_urls', # 'log': 'django.contrib.admin.templatetags.log' # } options['libraries'] = self.get_templatetag_libraries(libraries) super().__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options) def from_string(self, template_code): return Template(self.engine.from_string(template_code), self) def get_template(self, template_name): # self 是「模板引擎对象」 try: # self.engine 是 django.template.engine.Engine 类的实例,叫做「引擎对象」 # self.engine.get_template 的返回值是「模板对象」,django.template.base.Template 类的实例 # 下面这个 Template 是定义在当前模块中的类,该类的实例被称为「最终模板对象」 return Template(self.engine.get_template(template_name), self) except TemplateDoesNotExist as exc: reraise(exc, self) def get_templatetag_libraries(self, custom_libraries): """ Return a collation of template tag libraries from installed applications and the supplied custom_libraries argument. """ libraries = get_installed_libraries() libraries.update(custom_libraries) return libraries
class DjangoTemplates(BaseEngine): app_dirname = 'templates' def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() options.setdefault('debug', settings.TEMPLATE_DEBUG) options.setdefault('file_charset', settings.FILE_CHARSET) super(DjangoTemplates, self).__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options) def from_string(self, template_code): return Template(self.engine.from_string(template_code)) def get_template(self, template_name, dirs=_dirs_undefined): return Template(self.engine.get_template(template_name, dirs))
def test_debug_nodelist_name(self): template_name = 'index.html' engine = Engine(dirs=[TEMPLATE_DIR], debug=True) template = engine.get_template(template_name) name = template.nodelist[0].source[0].name self.assertTrue( name.endswith(template_name), 'Template loaded through cached loader has incorrect name for debug page: %s' % template_name, ) template = engine.get_template(template_name) name = template.nodelist[0].source[0].name self.assertTrue( name.endswith(template_name), 'Cached template loaded through cached loader has incorrect name for debug page: %s' % template_name, )
def setUpClass(cls): cls.engine = Engine(loaders=[( "django.template.loaders.locmem.Loader", { "index.html": "index", }, )], ) super().setUpClass()
def get_template_loader(cls): if not cls.template_loader: from django.template.loaders.filesystem import Loader from django.template.engine import Engine default_template_engine = Engine.get_default() cls.template_loader = Loader(default_template_engine) return cls.template_loader
def render_to_response(self, context, **response_kwargs): if self.template_string: context = RequestContext(request=self.request, dict_=context) engine = Engine.get_default() template = engine.from_string(self.template_string) return HttpResponse(template.render(context)) else: return super().render_to_response(context, **response_kwargs)
def test_load_template_source_empty_namespace(self): app_namespace_loader = Loader(Engine()) app_directory_loader = app_directories.Loader(Engine()) template_directory = app_directory_loader.load_template_source( 'admin/base.html') template_namespace = app_namespace_loader.load_template_source( ':admin/base.html') self.assertEquals(template_directory[0], template_namespace[0]) self.assertTrue( 'app_namespace:django.contrib.admin:' in template_namespace[1]) self.assertTrue('admin/base.html' in template_namespace[1]) self.assertRaises(TemplateDoesNotExist, app_namespace_loader.load_template_source, ':template')
def sample_template(): template_string = """ {% load djpt_limits %} {% djptlimit 'TimeLimit' total=3 %} {{ slow_rendering }} {% enddjptlimit %} """ return Engine.get_default().from_string(template_string)
def get_bricks_context(self): request = self.request context = make_context({}, request) for processor in Engine.get_default().template_context_processors: context.update(processor(request)) return context
def render_to_response(self, context, **response_kwargs): if self.template_string: context = RequestContext(request=self.request, dict_=context) engine = Engine.get_default() template = engine.from_string(self.template_string) return HttpResponse(template.render(context)) else: return super(ClassDetail, self).render_to_response(context, **response_kwargs)
class DjangoTemplates(BaseEngine): app_dirname = 'templates' def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() options.setdefault('debug', settings.DEBUG) options.setdefault('file_charset', settings.FILE_CHARSET) super(DjangoTemplates, self).__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options) def from_string(self, template_code): return Template(self.engine.from_string(template_code)) def get_template(self, template_name, dirs=_dirs_undefined): return Template(self.engine.get_template(template_name, dirs))
def create_engine(self, **kwargs): return Engine( loaders=[ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', ]), ], )
def test_cached_loader_priority(self): """ Check that the order of template loader works. Refs #21460. """ loaders = [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n')
def test_utf8_bytestring(self): """ Invalid UTF-8 encoding in bytestrings should raise a useful error """ engine = Engine() loader = engine.template_loaders[0] with self.assertRaises(UnicodeDecodeError): list(loader.get_template_sources(b'\xc3\xc3', ['/dir1']))
def setUp(self): self.engine = Engine( dirs=[TEMPLATE_DIR], loaders=[ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', ]), ], )
class RenderToStringTest(SimpleTestCase): def setUp(self): self.engine = Engine(dirs=[TEMPLATE_DIR]) def test_basic_context(self): self.assertEqual( self.engine.render_to_string('test_context.html', {'obj': 'test'}), 'obj:test\n', )
def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() options.setdefault('debug', settings.DEBUG) options.setdefault('file_charset', settings.FILE_CHARSET) libraries = options.get('libraries', {}) options['libraries'] = self.get_templatetag_libraries(libraries) super(DjangoTemplates, self).__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options)
def test_repr_empty(self): engine = Engine() self.assertEqual( repr(engine), "<Engine: app_dirs=False debug=False loaders=[(" "'django.template.loaders.cached.Loader', " "['django.template.loaders.filesystem.Loader'])] " "string_if_invalid='' file_charset='utf-8' builtins=[" "'django.template.defaulttags', 'django.template.defaultfilters', " "'django.template.loader_tags'] autoescape=True>")
def template_source(request): """ Return the source of a template, syntax-highlighted by Pygments if it's available. """ template_origin_name = request.GET.get('template_origin', None) if template_origin_name is None: return HttpResponseBadRequest('"template_origin" key is required') template_name = request.GET.get('template', template_origin_name) final_loaders = [] loaders = Engine.get_default().template_loaders for loader in loaders: if loader is not None: # When the loader has loaders associated with it, # append those loaders to the list. This occurs with # django.template.loaders.cached.Loader if hasattr(loader, 'loaders'): final_loaders += loader.loaders else: final_loaders.append(loader) for loader in final_loaders: if Origin: # django>=1.9 origin = Origin(template_origin_name) try: source = loader.get_contents(origin) break except TemplateDoesNotExist: pass else: # django<1.9 try: source, _ = loader.load_template_source(template_name) break except TemplateDoesNotExist: pass else: source = "Template Does Not Exist: %s" % (template_origin_name, ) try: from pygments import highlight from pygments.lexers import HtmlDjangoLexer from pygments.formatters import HtmlFormatter source = highlight(source, HtmlDjangoLexer(), HtmlFormatter()) source = mark_safe(source) source.pygmentized = True except ImportError: pass # Using SimpleTemplateResponse avoids running global context processors. return SimpleTemplateResponse('debug_toolbar/panels/template_source.html', { 'source': source, 'template_name': template_name })
def test_load_template_source_dotted_namespace(self): app_namespace_loader = Loader(Engine()) template_short = app_namespace_loader.load_template_source( 'admin:admin/base.html') template_dotted = app_namespace_loader.load_template_source( 'django.contrib.admin:admin/base.html') self.assertEquals(template_short[0], template_dotted[0])
def template_source(request): """ Return the source of a template, syntax-highlighted by Pygments if it's available. """ template_origin_name = request.GET.get("template_origin") if template_origin_name is None: return HttpResponseBadRequest('"template_origin" key is required') try: template_origin_name = signing.loads(template_origin_name) except Exception: return HttpResponseBadRequest('"template_origin" is invalid') template_name = request.GET.get("template", template_origin_name) final_loaders = [] loaders = Engine.get_default().template_loaders for loader in loaders: if loader is not None: # When the loader has loaders associated with it, # append those loaders to the list. This occurs with # django.template.loaders.cached.Loader if hasattr(loader, "loaders"): final_loaders += loader.loaders else: final_loaders.append(loader) for loader in final_loaders: origin = Origin(template_origin_name) try: source = loader.get_contents(origin) break except TemplateDoesNotExist: pass else: source = "Template Does Not Exist: {}".format(template_origin_name) try: from pygments import highlight from pygments.formatters import HtmlFormatter from pygments.lexers import HtmlDjangoLexer source = highlight(source, HtmlDjangoLexer(), HtmlFormatter()) source = mark_safe(source) source.pygmentized = True except ImportError: pass content = render_to_string( "debug_toolbar/panels/template_source.html", { "source": source, "template_name": template_name }, ) return JsonResponse({"content": content})
def __init__(self, loaders): self.template_cache = {} self._loaders = loaders self._cached_loaders = [] try: from django.template.loader import find_template_loader as _find_template_loader except: _find_template_loader = Engine.get_default().find_template_loader self._find_template_loader = _find_template_loader
class TemplateDirsOverrideTests(SimpleTestCase): DIRS = ((OTHER_DIR,), [OTHER_DIR]) def setUp(self): self.engine = Engine() def test_render_to_string(self): for dirs in self.DIRS: self.assertEqual(self.engine.render_to_string("test_dirs.html", dirs=dirs), "spam eggs\n") def test_get_template(self): for dirs in self.DIRS: template = self.engine.get_template("test_dirs.html", dirs=dirs) self.assertEqual(template.render(Context()), "spam eggs\n") def test_select_template(self): for dirs in self.DIRS: template = self.engine.select_template(["test_dirs.html"], dirs=dirs) self.assertEqual(template.render(Context()), "spam eggs\n")
def __init__(self): if has_engine: super(Loader, self).__init__(Engine.get_default()) else: super(Loader, self).__init__() include_pattern = getattr(settings, 'JINGO_INCLUDE_PATTERN', None) if include_pattern: self.include_re = re.compile(include_pattern) else: self.include_re = None
def __init__(self, forms_dir='forms', engine=None): if engine is None: engine = Engine.get_default() self._engine = engine self._forms_dirs = get_app_template_dirs(forms_dir) self._forms_loader = Loader(self) self.use_form_tags = False self.context_processors = self._engine.context_processors + ['template_forms.posted_answers']
def build_context(request, **kwargs): context = make_context({}, request) for processor in Engine.get_default().template_context_processors: context.update(processor(request)) context.update( kwargs) # Updated _after_ processors in order to avoid shadowing return context.flatten()
class TornadoTemplate(BaseEngine): app_dirname = 'tornado' def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() options.setdefault('debug', settings.DEBUG) options.setdefault('file_charset', settings.FILE_CHARSET) super(TornadoTemplate, self).__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options) def from_string(self, template_code): return Template(self.engine.from_string(template_code)) def get_template(self, template_name, dirs=_dirs_undefined): return Template(self.engine.get_template(template_name, dirs)) self.env = environment_cls(**options)