def test_load_working_egg(self): ttext = "{% load working_egg %}" egg_name = '%s/tagsegg.egg' % self.egg_dir with extend_sys_path(egg_name): engine = Engine(libraries={ 'working_egg': 'tagsegg.templatetags.working_egg', }) engine.from_string(ttext)
def test_unknown_block_tag(self): engine = Engine() msg = ( "Invalid block tag on line 1: 'foobar'. Did you forget to " "register or load this tag?" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("lala{% foobar %}")
def test_unknown_block_tag(self): engine = Engine() msg = ( "Invalid block tag on line 1: 'foobar'. Did you forget to " "register or load this tag?" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("lala{% foobar %}")
def test_load_working_egg(self): ttext = "{% load working_egg %}" egg_name = '%s/tagsegg.egg' % self.egg_dir with extend_sys_path(egg_name): engine = Engine(libraries={ 'working_egg': 'tagsegg.templatetags.working_egg', }) engine.from_string(ttext)
def test_extends_generic_template(self): """ #24338 -- Allow extending django.template.backends.django.Template objects. """ engine = Engine() parent = engine.from_string("{% block content %}parent{% endblock %}") child = engine.from_string("{% extends parent %}{% block content %}child{% endblock %}") self.assertEqual(child.render(Context({"parent": parent})), "child")
def test_include_template_argument(self): """ Support any render() supporting object """ engine = Engine() ctx = Context({"tmpl": engine.from_string("This worked!")}) outer_tmpl = engine.from_string("{% include tmpl %}") output = outer_tmpl.render(ctx) self.assertEqual(output, "This worked!")
def test_compile_tag_error(self): """ Errors raised while compiling nodes should include the token information. """ engine = Engine(debug=True) with self.assertRaises(RuntimeError) as e: engine.from_string("{% load bad_tag %}{% badtag %}") self.assertEqual(e.exception.template_debug["during"], "{% badtag %}")
def test_load_working_egg(self): ttext = "{% load working_egg %}" egg_name = "%s/tagsegg.egg" % self.egg_dir with extend_sys_path(egg_name): engine = Engine(libraries={"working_egg": "tagsegg.templatetags.working_egg"}) engine.from_string(ttext) with six.assertRaisesRegex(self, InvalidTemplateLibrary, msg): Engine(libraries={"broken_tag": "template_tests.broken_tag"})
def test_compile_tag_error(self): """ Errors raised while compiling nodes should include the token information. """ engine = Engine(debug=True) with self.assertRaises(RuntimeError) as e: engine.from_string("{% load bad_tag %}{% badtag %}") self.assertEqual(e.exception.template_debug['during'], '{% badtag %}')
def test_include_only(self): """ #15721 -- ``{% include %}`` and ``RequestContext`` should work together. """ engine = Engine(loaders=[("django.template.loaders.locmem.Loader", {"child": '{{ var|default:"none" }}'})]) request = RequestFactory().get("/") ctx = RequestContext(request, {"var": "parent"}) self.assertEqual(engine.from_string('{% include "child" %}').render(ctx), "parent") self.assertEqual(engine.from_string('{% include "child" only %}').render(ctx), "none")
def test_extends_generic_template(self): """ #24338 -- Allow extending django.template.backends.django.Template objects. """ engine = Engine() parent = engine.from_string('{% block content %}parent{% endblock %}') child = engine.from_string( '{% extends parent %}{% block content %}child{% endblock %}') self.assertEqual(child.render(Context({'parent': parent})), 'child')
def test_invalid_block_suggestion(self): """ #7876 -- Error messages should include the unexpected block name. """ engine = Engine() msg = ( "Invalid block tag on line 1: 'endblock', expected 'elif', 'else' " "or 'endif'. Did you forget to register or load this tag?") with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("{% if 1 %}lala{% endblock %}{% endif %}")
def test_invalid_block_suggestion(self): """ #7876 -- Error messages should include the unexpected block name. """ engine = Engine() with self.assertRaises(TemplateSyntaxError) as e: engine.from_string("{% if 1 %}lala{% endblock %}{% endif %}") self.assertEqual(e.exception.args[0], "Invalid block tag: 'endblock', expected 'elif', 'else' or 'endif'")
def test_include_template_argument(self): """ Support any render() supporting object """ engine = Engine() ctx = Context({ 'tmpl': engine.from_string('This worked!'), }) outer_tmpl = engine.from_string('{% include tmpl %}') output = outer_tmpl.render(ctx) self.assertEqual(output, 'This worked!')
def test_invalid_block_suggestion(self): """ #7876 -- Error messages should include the unexpected block name. """ engine = Engine() msg = ( "Invalid block tag on line 1: 'endblock', expected 'elif', 'else' " "or 'endif'. Did you forget to register or load this tag?" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("{% if 1 %}lala{% endblock %}{% endif %}")
def test_invalid_block_suggestion(self): """ Error messages should include the unexpected block name and be in all English. """ engine = Engine() msg = ( "Invalid block tag on line 1: 'endblock', expected 'elif', 'else' " "or 'endif'. Did you forget to register or load this tag?") with self.settings(USE_I18N=True), translation.override('de'): with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("{% if 1 %}lala{% endblock %}{% endif %}")
def test_compile_tag_error(self): """ Errors raised while compiling nodes should include the token information. """ engine = Engine( debug=True, libraries={'bad_tag': 'template_tests.templatetags.bad_tag'}, ) with self.assertRaises(RuntimeError) as e: engine.from_string("{% load bad_tag %}{% badtag %}") self.assertEqual(e.exception.template_debug['during'], '{% badtag %}')
def test_invalid_block_suggestion(self): """ Error messages should include the unexpected block name and be in all English. """ engine = Engine() msg = ( "Invalid block tag on line 1: 'endblock', expected 'elif', 'else' " "or 'endif'. Did you forget to register or load this tag?" ) with self.settings(USE_I18N=True), translation.override('de'): with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("{% if 1 %}lala{% endblock %}{% endif %}")
def test_invalid_block_suggestion(self): """ #7876 -- Error messages should include the unexpected block name. """ engine = Engine() with self.assertRaises(TemplateSyntaxError) as e: engine.from_string("{% if 1 %}lala{% endblock %}{% endif %}") self.assertEqual( e.exception.args[0], "Invalid block tag: 'endblock', expected 'elif', 'else' or 'endif'", )
def test_include_only(self): """ #15721 -- ``{% include %}`` and ``RequestContext`` should work together. """ engine = Engine(loaders=[ ('django.template.loaders.locmem.Loader', { 'child': '{{ var|default:"none" }}', }), ]) request = RequestFactory().get('/') ctx = RequestContext(request, {'var': 'parent'}) self.assertEqual(engine.from_string('{% include "child" %}').render(ctx), 'parent') self.assertEqual(engine.from_string('{% include "child" only %}').render(ctx), 'none')
def test_compile_filter_expression_error(self): """ 19819 -- Make sure the correct token is highlighted for FilterExpression errors. """ engine = Engine(debug=True) msg = "Could not parse the remainder: '@bar' from 'foo@bar'" with self.assertRaisesMessage(TemplateSyntaxError, msg) as e: engine.from_string("{% if 1 %}{{ foo@bar }}{% endif %}") debug = e.exception.template_debug self.assertEqual((debug["start"], debug["end"]), (10, 23)) self.assertEqual((debug["during"]), "{{ foo@bar }}")
def test_include_only(self): """ #15721 -- ``{% include %}`` and ``RequestContext`` should work together. """ engine = Engine(loaders=[ ('django.template.loaders.locmem.Loader', { 'child': '{{ var|default:"none" }}', }), ]) request = RequestFactory().get('/') ctx = RequestContext(request, {'var': 'parent'}) self.assertEqual(engine.from_string('{% include "child" %}').render(ctx), 'parent') self.assertEqual(engine.from_string('{% include "child" only %}').render(ctx), 'none')
def test_compile_filter_expression_error(self): """ 19819 -- Make sure the correct token is highlighted for FilterExpression errors. """ engine = Engine(debug=True) msg = "Could not parse the remainder: '@bar' from 'foo@bar'" with self.assertRaisesMessage(TemplateSyntaxError, msg) as e: engine.from_string("{% if 1 %}{{ foo@bar }}{% endif %}") debug = e.exception.template_debug self.assertEqual((debug['start'], debug['end']), (10, 23)) self.assertEqual((debug['during']), '{{ foo@bar }}')
def test_filter(self): engine = Engine(libraries=LIBRARIES) t = engine.from_string("{% load custom %}{{ string|trim:5 }}") self.assertEqual( t.render(Context({"string": "abcdefghijklmnopqrstuvwxyz"})), "abcde" )
class SSISecurityTests(SimpleTestCase): def setUp(self): self.ssi_dir = os.path.join(ROOT, "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 test_correct_exception_index(self): tests = [ ('{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% endfor %}', (38, 56)), ('{% load bad_tag %}{% for i in range %}{% for j in range %}' '{% badsimpletag %}{% endfor %}{% endfor %}', (58, 76)), ('{% load bad_tag %}{% for i in range %}{% badsimpletag %}' '{% for j in range %}Hello{% endfor %}{% endfor %}', (38, 56)), ('{% load bad_tag %}{% for i in range %}{% for j in five %}' '{% badsimpletag %}{% endfor %}{% endfor %}', (38, 57)), ('{% load bad_tag %}{% for j in five %}{% badsimpletag %}{% endfor %}', (18, 37)), ] context = Context({ 'range': range(5), 'five': 5, }) engine = Engine( debug=True, libraries={'bad_tag': 'template_tests.templatetags.bad_tag'}) for source, expected_error_source_index in tests: template = engine.from_string(source) try: template.render(context) except (RuntimeError, TypeError) as e: debug = e.template_debug self.assertEqual((debug['start'], debug['end']), expected_error_source_index)
class SSISecurityTests(SimpleTestCase): def setUp(self): self.ssi_dir = os.path.join(ROOT, "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), '')
class DjangoRenderer(TemplateRenderer): """ Renders Django templates. :param engine: a Django template engine object or keyword arguments for its constructor :param package_paths: if given, looks up the directories containing the given package and fills in or extends the ``dirs`` argument for :class:`~django.template.Engine`. The value will be interpreted by :func:`~asphalt.templating.util.package_to_directory`. """ __slots__ = 'engine' def __init__(self, engine: Union[Engine, Dict[str, Any]] = None, package_paths: Iterable[str] = ()): assert check_argument_types() self.engine = engine or {} if isinstance(self.engine, dict): self.engine.setdefault('dirs', []).extend(package_to_directory(pkg) for pkg in package_paths) self.engine = Engine(**self.engine) def render(self, template: str, **vars) -> str: template = self.engine.get_template(template) context = Context(vars) return template.render(context) def render_string(self, source: str, **vars) -> str: template = self.engine.from_string(source) context = Context(vars) return template.render(context)
class Text: def __init__(self, template: str) -> None: self._engine = Engine() self._template = self._engine.from_string(template) def render(self, context: dict) -> str: return self._template.render(Context(context=context))
def create_site(name, directory=SITE_DIR, templates_dir=TEMPLATES_DIR, static_dir=RESOURCES_DIR): if not directory: sys.stderr.write("Please provide a site name, e.g. %s <site_name>\n\n" % NAME) sys.exit(1) sys.stdout.write("\tCopying site templates to %s\n" % directory) # Generate manage.py from django.template import Engine, Context engine = Engine() f = open(os.path.join(os.path.dirname(templates_dir), "manage.txt")) template = engine.from_string(f.read()) f.close() managepy_file_contents = template.render(Context({"site_name": name})) managepy_file = open(os.path.join(BASE_DIR, "manage.py"), "w+") managepy_file.write(managepy_file_contents) managepy_file.close() os.chmod(os.path.join(BASE_DIR, "manage.py"), 0755) # copy template framework into site directory shutil.copytree("%s/" % templates_dir, directory, ignore=shutil.ignore_patterns(".svn")) site_resources = "%s/%s" % (static_dir, name) # make static dirs for static_dir in STATIC_DIRS: try: os.makedirs("%s/%s" % (site_resources, static_dir)) sys.stdout.write("\tCreated %s in %s\n" % (static_dir, site_resources)) except: pass
class DjangoRenderer(TemplateRenderer): """ Renders Django templates. :param engine: a Django template engine object or keyword arguments for its constructor :param package_paths: if given, looks up the directories containing the given package and fills in or extends the ``dirs`` argument for :class:`~django.template.Engine`. The value will be interpreted by :func:`~asphalt.templating.util.package_to_directory`. """ __slots__ = "engine" def __init__( self, engine: Engine | dict[str, Any] = None, package_paths: Iterable[str] = (), ) -> None: self.engine = engine or {} # type: Engine if isinstance(self.engine, dict): self.engine.setdefault("dirs", []).extend( package_to_directory(pkg) for pkg in package_paths) self.engine = Engine(**self.engine) def render(self, template: str, **vars) -> str: compiled_template = self.engine.get_template(template) context = Context(vars) return compiled_template.render(context) def render_string(self, source: str, **vars) -> str: template = self.engine.from_string(source) context = Context(vars) return template.render(context)
def test_filter(self): engine = Engine(libraries=LIBRARIES) t = engine.from_string("{% load custom %}{{ string|trim:5 }}") self.assertEqual( t.render(Context({"string": "abcdefghijklmnopqrstuvwxyz"})), "abcde" )
def __init__(self, code, context, language='en', **kwargs): ctx = Context(context) kw = kwargs.copy() email_template = EmailTemplate.objects.get(code=code) translated_field = '_' + language if app_settings.MODELATED_TRANSLATE else '' subject = getattr(email_template, 'subject{}'.format(translated_field)) body = getattr(email_template, 'body{}'.format(translated_field)) engine = Engine() subject = engine.from_string(subject) body = engine.from_string(body) kw['subject'] = subject.render(ctx) kw['body'] = body.render(ctx) super(TemplateEmailMessage, self).__init__(**kw)
def test_correct_exception_index(self): tests = [ ('{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% endfor %}', (38, 56)), ( '{% load bad_tag %}{% for i in range %}{% for j in range %}' '{% badsimpletag %}{% endfor %}{% endfor %}', (58, 76) ), ( '{% load bad_tag %}{% for i in range %}{% badsimpletag %}' '{% for j in range %}Hello{% endfor %}{% endfor %}', (38, 56) ), ( '{% load bad_tag %}{% for i in range %}{% for j in five %}' '{% badsimpletag %}{% endfor %}{% endfor %}', (38, 57) ), ('{% load bad_tag %}{% for j in five %}{% badsimpletag %}{% endfor %}', (18, 37)), ] context = Context({ 'range': range(5), 'five': 5, }) engine = Engine(debug=True, libraries={'bad_tag': 'template_tests.templatetags.bad_tag'}) for source, expected_error_source_index in tests: template = engine.from_string(source) try: template.render(context) except (RuntimeError, TypeError) as e: debug = e.template_debug self.assertEqual((debug['start'], debug['end']), expected_error_source_index)
def test_no_render_side_effect(self): """ #23441 -- InclusionNode shouldn't modify its nodelist at render time. """ engine = Engine(app_dirs=True, libraries=LIBRARIES) template = engine.from_string('{% load inclusion %}{% inclusion_no_params %}') count = template.nodelist.get_nodes_by_type(Node) template.render(Context({})) self.assertEqual(template.nodelist.get_nodes_by_type(Node), count)
def test_textnode_repr(self): engine = Engine() for temptext, reprtext in [ ("Hello, world!", "<TextNode: 'Hello, world!'>"), ("One\ntwo.", "<TextNode: 'One\\ntwo.'>"), ]: template = engine.from_string(temptext) texts = template.nodelist.get_nodes_by_type(TextNode) self.assertEqual(repr(texts[0]), reprtext)
def test_no_render_side_effect(self): """ #23441 -- InclusionNode shouldn't modify its nodelist at render time. """ engine = Engine(app_dirs=True, libraries=LIBRARIES) template = engine.from_string('{% load inclusion %}{% inclusion_no_params %}') count = template.nodelist.get_nodes_by_type(Node) template.render(Context({})) self.assertEqual(template.nodelist.get_nodes_by_type(Node), count)
def test_textnode_repr(self): engine = Engine() for temptext, reprtext in [ ("Hello, world!", "<TextNode: 'Hello, world!'>"), ("One\ntwo.", "<TextNode: 'One\\ntwo.'>"), ]: template = engine.from_string(temptext) texts = template.nodelist.get_nodes_by_type(TextNode) self.assertEqual(repr(texts[0]), reprtext)
def test_render_context_is_cleared(self): """ #24555 -- InclusionNode should push and pop the render_context stack when rendering. Otherwise, leftover values such as blocks from extending can interfere with subsequent rendering. """ engine = Engine(app_dirs=True, libraries=LIBRARIES) template = engine.from_string('{% load inclusion %}{% inclusion_extends1 %}{% inclusion_extends2 %}') self.assertEqual(template.render(Context({})).strip(), 'one\ntwo')
def test_render_context_is_cleared(self): """ #24555 -- InclusionNode should push and pop the render_context stack when rendering. Otherwise, leftover values such as blocks from extending can interfere with subsequent rendering. """ engine = Engine(app_dirs=True, libraries=LIBRARIES) template = engine.from_string('{% load inclusion %}{% inclusion_extends1 %}{% inclusion_extends2 %}') self.assertEqual(template.render(Context({})).strip(), 'one\ntwo')
def test_include_only(self): """ #15721 -- ``{% include %}`` and ``RequestContext`` should work together. """ engine = Engine(loaders=[ ( "django.template.loaders.locmem.Loader", { "child": '{{ var|default:"none" }}', }, ), ]) request = self.request_factory.get("/") ctx = RequestContext(request, {"var": "parent"}) self.assertEqual( engine.from_string('{% include "child" %}').render(ctx), "parent") self.assertEqual( engine.from_string('{% include "child" only %}').render(ctx), "none")
def send_templated_email(template_name, context, recipient_list, from_email=settings.DEFAULT_FROM_EMAIL, attachment_filename=None, attachment_data=None): """ Sends an email using a template stored in the database (based on the template name) Also supports attaching a file """ # Get template from database, render it using the provided context template_engine = Engine() email_template = EmailTemplate.objects.get(name=template_name) subject_template = template_engine.from_string(email_template.subject) body_template = template_engine.from_string(email_template.body) email_context = Context(context) email_subject = subject_template.render(email_context) email_body = body_template.render(email_context) email_body_full = render_to_string( 'emails/default.html', context={'rendered_email_body': email_body}) # Send the email text_message = strip_tags(email_body_full) email = EmailMultiAlternatives( to=recipient_list, from_email=from_email, subject=email_subject, body=text_message, ) email.attach_alternative(email_body_full, "text/html") # Attachment? if attachment_filename: if attachment_data: email.attach(attachment_filename, attachment_data) else: email.attach_file(attachment_filename) elif attachment_data: email.attach('attachment', attachment_data) email.send()
def test_template(self): # Templates can be created from unicode strings. engine = Engine() t1 = engine.from_string('ŠĐĆŽćžšđ {{ var }}') # Templates can also be created from bytestrings. These are assumed to # be encoded using UTF-8. s = b'\xc5\xa0\xc4\x90\xc4\x86\xc5\xbd\xc4\x87\xc5\xbe\xc5\xa1\xc4\x91 {{ var }}' t2 = engine.from_string(s) with self.assertRaises(TemplateEncodingError): engine.from_string(b'\x80\xc5\xc0') # Contexts can be constructed from unicode or UTF-8 bytestrings. Context({b"var": b"foo"}) Context({"var": b"foo"}) c3 = Context({b"var": "Đđ"}) Context({"var": b"\xc4\x90\xc4\x91"}) # Since both templates and all four contexts represent the same thing, # they all render the same (and are returned as unicode objects and # "safe" objects as well, for auto-escaping purposes). self.assertEqual(t1.render(c3), t2.render(c3)) self.assertIsInstance(t1.render(c3), six.text_type) self.assertIsInstance(t1.render(c3), SafeData)
def test_template(self): # Templates can be created from unicode strings. engine = Engine() t1 = engine.from_string('ŠĐĆŽćžšđ {{ var }}') # Templates can also be created from bytestrings. These are assumed to # be encoded using UTF-8. s = b'\xc5\xa0\xc4\x90\xc4\x86\xc5\xbd\xc4\x87\xc5\xbe\xc5\xa1\xc4\x91 {{ var }}' t2 = engine.from_string(s) with self.assertRaises(TemplateEncodingError): engine.from_string(b'\x80\xc5\xc0') # Contexts can be constructed from unicode or UTF-8 bytestrings. Context({b"var": b"foo"}) Context({"var": b"foo"}) c3 = Context({b"var": "Đđ"}) Context({"var": b"\xc4\x90\xc4\x91"}) # Since both templates and all four contexts represent the same thing, # they all render the same (and are returned as unicode objects and # "safe" objects as well, for auto-escaping purposes). self.assertEqual(t1.render(c3), t2.render(c3)) self.assertIsInstance(t1.render(c3), str) self.assertIsInstance(t1.render(c3), SafeData)
def test_no_wrapped_exception(self): """ # 16770 -- The template system doesn't wrap exceptions, but annotates them. """ engine = Engine(debug=True) c = Context({"coconuts": lambda: 42 / 0}) t = engine.from_string("{{ coconuts }}") with self.assertRaises(ZeroDivisionError) as e: t.render(c) debug = e.exception.template_debug self.assertEqual(debug['start'], 0) self.assertEqual(debug['end'], 14)
def test_no_wrapped_exception(self): """ # 16770 -- The template system doesn't wrap exceptions, but annotates them. """ engine = Engine(debug=True) c = Context({"coconuts": lambda: 42 / 0}) t = engine.from_string("{{ coconuts }}") with self.assertRaises(ZeroDivisionError) as e: t.render(c) debug = e.exception.template_debug self.assertEqual(debug["start"], 0) self.assertEqual(debug["end"], 14)
def index(request): person = request.POST.get('name', "") if person == "": person = request.GET.get('name', "") template_code = '<!DOCTYPE html><html><body>\ <form action="/" method="post">\ First name:<br>\ <input type="text" name="name" value="">\ <input type="submit" value="Submit">\ </form><h2>Hello ' + person + '</h2></body></html>' engine = Engine() template = engine.from_string(template_code=template_code) context = RequestContext(request) context.push({"name": "Adrian"}) return HttpResponse(template.render(context))
def test_correct_exception_index(self): tests = [ ( "{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% endfor %}", (38, 56), ), ( "{% load bad_tag %}{% for i in range %}{% for j in range %}" "{% badsimpletag %}{% endfor %}{% endfor %}", (58, 76), ), ( "{% load bad_tag %}{% for i in range %}{% badsimpletag %}" "{% for j in range %}Hello{% endfor %}{% endfor %}", (38, 56), ), ( "{% load bad_tag %}{% for i in range %}{% for j in five %}" "{% badsimpletag %}{% endfor %}{% endfor %}", (38, 57), ), ( "{% load bad_tag %}{% for j in five %}{% badsimpletag %}{% endfor %}", (18, 37), ), ] context = Context({ "range": range(5), "five": 5, }) engine = Engine( debug=True, libraries={"bad_tag": "template_tests.templatetags.bad_tag"}) for source, expected_error_source_index in tests: template = engine.from_string(source) try: template.render(context) except (RuntimeError, TypeError) as e: debug = e.template_debug self.assertEqual((debug["start"], debug["end"]), expected_error_source_index)
def create_site(name, directory=SITE_DIR, templates_dir=TEMPLATES_DIR, static_dir=RESOURCES_DIR): if not directory: sys.stderr.write( "Please provide a site name, e.g. %s <site_name>\n\n" % NAME) sys.exit(1) sys.stdout.write("\tCopying site templates to %s\n" % directory) # Generate manage.py from django.template import Engine, Context engine = Engine() f = open(os.path.join(os.path.dirname(templates_dir), 'manage.txt')) template = engine.from_string(f.read()) f.close() managepy_file_contents = template.render(Context({'site_name': name})) managepy_file = open(os.path.join(BASE_DIR, 'manage.py'), 'w+') managepy_file.write(managepy_file_contents) managepy_file.close() os.chmod(os.path.join(BASE_DIR, 'manage.py'), 0755) # copy template framework into site directory shutil.copytree("%s/" % templates_dir, directory, ignore=shutil.ignore_patterns('.svn')) site_resources = "%s/%s" % (static_dir, name) # make static dirs for static_dir in STATIC_DIRS: try: os.makedirs("%s/%s" % (site_resources, static_dir)) sys.stdout.write("\tCreated %s in %s\n" % (static_dir, site_resources)) except: pass
def get_traceback_text(self): "Return plain text version of debug 500 HTTP error page." DEBUG_ENGINE = Engine(debug=True) t = DEBUG_ENGINE.from_string(TECHNICAL_500_TEXT_TEMPLATE_EXPAND_BODY) c = Context(self.get_traceback_data(), autoescape=False, use_l10n=False) return t.render(c)
def test_render_a_variable_template(self): _engine = Engine() _template = _engine.from_string("Simple replacement {{ target }}.") _context = Context({"target": "Claudio Santos"}) self.assertTrue( _template.render(_context) == "Simple replacement Claudio Santos.")
def render(self): """Render the summary.""" engine = Engine() return engine.from_string(SUMMARY_TEMPLATE).render( Context(self.__dict__))
def test_decorated_filter(self): engine = Engine(libraries=LIBRARIES) t = engine.from_string('{% load custom %}{{ name|make_data_div }}') self.assertEqual(t.render(Context({'name': 'foo'})), '<div data-name="foo"></div>')
# Give some variables to print. Note that we have to convert the # numbers to string ahead of time, because Django wants to do # l10n-specific stuff with numbers and barfs if you attempt to display # a number without having settings set up. variables = { 'name': 'world', 'whom': 'template', 'numbers': [str(i) for i in range(200)] } compiler = Compiler() margate_func = compiler.compile(expression) engine = Engine() template = engine.from_string(expression) context = Context(variables) def margate_render(): return margate_func(**variables) def django_render(): return template.render(context) def do_performance_test(): assert margate_render() == django_render() iterations = 1000
def test_decorated_filter(self): engine = Engine(libraries=LIBRARIES) t = engine.from_string('{% load custom %}{{ name|make_data_div }}') self.assertEqual(t.render(Context({'name': 'foo'})), '<div data-name="foo"></div>')