Python django.template.Engine() Examples

The following are 30 code examples of django.template.Engine(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.template , or try the search function .
Example #1
Source File: test_extends.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_block_override_in_extended_included_template(self):
        """
        ExtendsNode.find_template() initializes history with self.origin
        (#28071).
        """
        engine = Engine(
            loaders=[
                ['django.template.loaders.locmem.Loader', {
                    'base.html': "{% extends 'base.html' %}{% block base %}{{ block.super }}2{% endblock %}",
                    'included.html':
                        "{% extends 'included.html' %}{% block included %}{{ block.super }}B{% endblock %}",
                }],
                ['django.template.loaders.locmem.Loader', {
                    'base.html': "{% block base %}1{% endblock %}{% include 'included.html' %}",
                    'included.html': "{% block included %}A{% endblock %}",
                }],
            ],
        )
        template = engine.get_template('base.html')
        self.assertEqual(template.render(Context({})), '12AB') 
Example #2
Source File: static.py    From bioforum with MIT License 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
        c = Context()
    else:
        c = {}
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example #3
Source File: static.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c = Context({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example #4
Source File: start.py    From DeerU with GNU General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        self.type = options['type']
        self.name = options['name']
        management.call_command('startapp', self.name)
        dir_name = ['management', Path('management/commands')]
        self.mk_dir(dir_name)

        if self.type == 'theme':
            dir_name = ['static', Path('static/' + self.name), 'templates', Path('templates/' + self.name)]
            self.mk_dir(dir_name)

        context = Context({
            'app_name': self.name,
            'app_camel_name': self.name[0].upper() + self.name[1:],
            'app_upper_name': self.name.upper(),
            'deeru_type': self.type
        }, autoescape=False)

        for template_name, new_file in self.get_app_templates():
            template = Engine().from_string(self.get_template_str(template_name))
            content = template.render(context)
            new_file.write_text(content) 
Example #5
Source File: test_filesystem.py    From django-tenants with MIT License 6 votes vote down vote up
def setUpClass(cls):
        test_app_root = settings.TENANT_APPS_DIR
        settings.MULTITENANT_TEMPLATE_DIRS = [
            os.path.join(test_app_root, "tenants/%s/templates")
        ]

        cls.engine = Engine(
            loaders=[
                (
                    "django_tenants.template.loaders.cached.Loader",
                    ["django_tenants.template.loaders.filesystem.Loader"],
                )
            ]
        )

        super().setUpClass() 
Example #6
Source File: test_cached.py    From django-tenants with MIT License 6 votes vote down vote up
def setUpClass(cls):
        test_app_root = settings.TENANT_APPS_DIR
        settings.MULTITENANT_TEMPLATE_DIRS = [
            os.path.join(test_app_root, "tenants/%s/templates")
        ]

        cls.engine = Engine(
            loaders=[
                (
                    "django_tenants.template.loaders.cached.Loader",
                    ["django_tenants.template.loaders.filesystem.Loader"],
                )
            ]
        )

        super().setUpClass() 
Example #7
Source File: static.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
        c = Context()
    else:
        c = {}
    files = []
    for f in fullpath.iterdir():
        if not f.name.startswith('.'):
            url = str(f.relative_to(fullpath))
            if f.is_dir():
                url += '/'
            files.append(url)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example #8
Source File: static.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c = Context({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example #9
Source File: static.py    From python2017 with MIT License 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
        c = Context()
    else:
        c = {}
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example #10
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_url_reverse_view_name(self):
        """
        #19827 -- url tag should keep original strack trace when reraising
        exception.
        """
        t = Engine().from_string('{% url will_not_match %}')
        c = Context()
        try:
            t.render(c)
        except NoReverseMatch:
            tb = sys.exc_info()[2]
            depth = 0
            while tb.tb_next is not None:
                tb = tb.tb_next
                depth += 1
            self.assertGreater(depth, 5, "The traceback context was lost when reraising the traceback.") 
Example #11
Source File: static.py    From python with Apache License 2.0 6 votes vote down vote up
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
        c = Context()
    else:
        c = {}
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c)) 
Example #12
Source File: test_extends.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_recursive_multiple_loaders(self):
        engine = Engine(
            dirs=[os.path.join(RECURSIVE, 'fs')],
            loaders=[(
                'django.template.loaders.locmem.Loader', {
                    'one.html': (
                        '{% extends "one.html" %}{% block content %}{{ block.super }} locmem-one{% endblock %}'
                    ),
                    'two.html': (
                        '{% extends "two.html" %}{% block content %}{{ block.super }} locmem-two{% endblock %}'
                    ),
                    'three.html': (
                        '{% extends "three.html" %}{% block content %}{{ block.super }} locmem-three{% endblock %}'
                    ),
                }
            ), 'django.template.loaders.filesystem.Loader'],
        )
        template = engine.get_template('one.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'three locmem-three two locmem-two one locmem-one') 
Example #13
Source File: test_extends.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_unique_history_per_loader(self):
        """
        Extending should continue even if two loaders return the same
        name for a template.
        """
        engine = Engine(
            loaders=[
                ['django.template.loaders.locmem.Loader', {
                    'base.html': '{% extends "base.html" %}{% block content %}{{ block.super }} loader1{% endblock %}',
                }],
                ['django.template.loaders.locmem.Loader', {
                    'base.html': '{% block content %}loader2{% endblock %}',
                }],
            ]
        )
        template = engine.get_template('base.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'loader2 loader1') 
Example #14
Source File: defaults.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def page_not_found(request, template_name='404.html'):
    """
    Default 404 handler.

    Templates: :template:`404.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/')
    """
    context = {'request_path': request.path}
    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None             # Django will use DEFAULT_CONTENT_TYPE
    except TemplateDoesNotExist:
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {{ request_path }} was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'
    return http.HttpResponseNotFound(body, content_type=content_type) 
Example #15
Source File: test_extends_relative.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_dir1_extend1(self):
        engine = Engine(dirs=[RELATIVE])
        template = engine.get_template('dir1/one1.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'three two one dir1 one') 
Example #16
Source File: test_extends_relative.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_dir1_extend(self):
        engine = Engine(dirs=[RELATIVE])
        template = engine.get_template('dir1/one.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'three two one dir1 one') 
Example #17
Source File: test_logging.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_log_on_variable_does_not_exist_silent(self):
        class TestObject:
            class SilentDoesNotExist(Exception):
                silent_variable_failure = True

            @property
            def template_name(self):
                return "template_name"

            @property
            def template(self):
                return Engine().from_string('')

            @property
            def article(self):
                raise TestObject.SilentDoesNotExist("Attribute does not exist.")

            def __iter__(self):
                return iter(attr for attr in dir(TestObject) if attr[:2] != "__")

            def __getitem__(self, item):
                return self.__dict__[item]

        with self.assertLogs('django.template', self.loglevel) as cm:
            Variable('article').resolve(TestObject())

        self.assertEqual(len(cm.records), 1)
        log_record = cm.records[0]
        self.assertEqual(
            log_record.getMessage(),
            "Exception while resolving variable 'article' in template 'template_name'."
        )
        self.assertIsNotNone(log_record.exc_info)
        raised_exception = log_record.exc_info[1]
        self.assertEqual(str(raised_exception), 'Attribute does not exist.') 
Example #18
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_node_origin(self):
        """
        #25848 -- Set origin on Node so debugging tools can determine which
        template the node came from even if extending or including templates.
        """
        template = Engine().from_string('content')
        for node in template.nodelist:
            self.assertEqual(node.origin, template.origin) 
Example #19
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
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') 
Example #20
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_super_errors(self):
        """
        #18169 -- NoReverseMatch should not be silence in block.super.
        """
        engine = Engine(app_dirs=True)
        t = engine.get_template('included_content.html')
        with self.assertRaises(NoReverseMatch):
            t.render(Context()) 
Example #21
Source File: test_callables.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUpClass(cls):
        cls.engine = Engine()
        super().setUpClass() 
Example #22
Source File: test_extends_relative.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_dir1_extend2(self):
        engine = Engine(dirs=[RELATIVE])
        template = engine.get_template('dir1/one2.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'three two one dir1 one') 
Example #23
Source File: test_extends_relative.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_dir1_extend3(self):
        engine = Engine(dirs=[RELATIVE])
        template = engine.get_template('dir1/one3.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'three two one dir1 one') 
Example #24
Source File: test_extends_relative.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_dir2_extend(self):
        engine = Engine(dirs=[RELATIVE])
        template = engine.get_template('dir1/dir2/one.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'three two one dir2 one') 
Example #25
Source File: test_extends_relative.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_normal_include(self):
        engine = Engine(dirs=[RELATIVE])
        template = engine.get_template('dir1/dir2/inc2.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'dir2 include') 
Example #26
Source File: test_extends_relative.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_dir2_include(self):
        engine = Engine(dirs=[RELATIVE])
        template = engine.get_template('dir1/dir2/inc1.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'three') 
Example #27
Source File: test_extends_relative.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_include_error(self):
        engine = Engine(dirs=[RELATIVE])
        msg = (
            "The relative path '\"./../three.html\"' points outside the file "
            "hierarchy that template 'error_include.html' is in."
        )
        with self.assertRaisesMessage(TemplateSyntaxError, msg):
            engine.render_to_string('error_include.html') 
Example #28
Source File: test_extends_relative.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_mixing1(self):
        engine = Engine(dirs=[RELATIVE])
        template = engine.get_template('dir1/two.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'three two one dir2 one dir1 two') 
Example #29
Source File: test_custom.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
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>') 
Example #30
Source File: test_extends_relative.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_mixing2(self):
        engine = Engine(dirs=[RELATIVE])
        template = engine.get_template('dir1/three.html')
        output = template.render(Context({}))
        self.assertEqual(output.strip(), 'three dir1 three')