def test_load_template(self): app_namespace_loader = Loader(Engine()) app_directory_loader = app_directories.Loader(Engine()) template_directory = app_directory_loader.load_template( 'admin/base.html')[0] template_namespace = app_namespace_loader.load_template( 'admin:admin/base.html')[0] context = Context({}) self.assertEquals(template_directory.render(context), template_namespace.render(context))
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 generate(): template = Template("title {{ my_title }}\nbase {{ base }}", engine=Engine()) title = title_e.get() base = base_e.get() context = Context({"my_title": title, "base": base}) edit_text.insert(INSERT, template.render(context))
def test_loaders_dirs_empty(self): """An empty dirs list in loaders overrides top level dirs.""" engine = Engine(dirs=[TEMPLATE_DIR], loaders=[('django.template.loaders.filesystem.Loader', [])]) with self.assertRaises(TemplateDoesNotExist): engine.get_template('index.html')
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)
def setUpClass(cls): cls.engine = Engine( loaders=[('django.template.loaders.locmem.Loader', { 'index.html': 'index', })], ) super(LocmemLoaderTests, cls).setUpClass()
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 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
def get_engine(self, templates): loaders = [( "django.template.loaders.cached.Loader", [("django.template.loaders.locmem.Loader", templates)], )] return Engine(loaders=loaders, libraries={"i18n": "django.templatetags.i18n"})
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 setUpClass(cls): cls.engine = Engine(loaders=[( "django.template.loaders.locmem.Loader", { "index.html": "index", }, )], ) super().setUpClass()
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 create_engine(self, **kwargs): return Engine( loaders=[ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', ]), ], )
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 setUp(self): self.engine = Engine( dirs=[TEMPLATE_DIR], loaders=[ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', ]), ], )
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 __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_polygons_templates(self): # Accessing Polygon attributes in templates should work. engine = Engine() template = engine.from_string("{{ polygons.0.wkt }}") polygons = [ OGRGeometry(p.wkt) for p in self.geometries.multipolygons[:2] ] content = template.render(Context({"polygons": polygons})) self.assertIn("MULTIPOLYGON (((100", content)
def render_email(request, text, key): """ Render invite email context from template object. """ context = Engine().from_string(text).render(Context( {'creator': key.creator.first_name + " " + key.creator.last_name, 'entity_id': key.sp.entity_id, 'activation_link': get_activation_link(request, key), 'valid_until': key.valid_until})) return context
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", {}) options["libraries"] = self.get_templatetag_libraries(libraries) super().__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options)
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', {}) options['libraries'] = self.get_templatetag_libraries(libraries) super().__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options)
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_template(self): if django.VERSION >= (1, 8): loader = Loader(Engine()) else: loader = Loader() res = list(loader.get_template_sources('base.html')) self.assertGreaterEqual(len(res), 1) cont = loader.load_template_source('base.html') self.assertGreaterEqual(len(cont[0]), 10)
def render_to_string(template_name, context): """ This is to replace django.template.loader.render_to_string since that now expects a dict context, instead of a Context(). This uses default Django Template Engine to render the template and context, like it did in Django <= 1.10. For more info, see: - https://code.djangoproject.com/ticket/27722 - https://docs.djangoproject.com/en/1.11/releases/1.11/#django-template-backends-django-template-render-prohibits-non-dict-context """ return Engine(app_dirs=True).render_to_string(template_name, context=context)
def test_context_comparable(self): # Create an engine without any context processors. engine = Engine() test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}} # test comparing RequestContext to prevent problems if somebody # adds __eq__ in the future request = RequestFactory().get('/') self.assertEqual( RequestContext(request, dict_=test_data, engine=engine), RequestContext(request, dict_=test_data, engine=engine))
def setUp(self): """ Setup theming Loader instance. """ super().setUp() self.engine = Engine( dirs=[TEMPLATE_DIR], loaders=[ 'theming.template.loaders.theme.Loader', 'django.template.loaders.app_directories.Loader', ], ) self.loader = Loader(engine=self.engine) self.addCleanup(cleanup_current_request_and_theme)
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 test_repr(self): engine = Engine( dirs=[TEMPLATE_DIR], context_processors=['django.template.context_processors.debug'], debug=True, loaders=['django.template.loaders.filesystem.Loader'], string_if_invalid='x', file_charset='utf-16', libraries={'custom': 'template_tests.templatetags.custom'}, autoescape=False, ) self.assertEqual( repr(engine), f"<Engine: dirs=[{TEMPLATE_DIR!r}] app_dirs=False " "context_processors=['django.template.context_processors.debug'] " "debug=True loaders=['django.template.loaders.filesystem.Loader'] " "string_if_invalid='x' file_charset='utf-16' " "libraries={'custom': 'template_tests.templatetags.custom'} " "builtins=['django.template.defaulttags', " "'django.template.defaultfilters', 'django.template.loader_tags'] " "autoescape=False>")
def test_cached_loader_priority(self): """ 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 __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)