Skip to content
Myr

include tags are now able to select between multiple templates

Before adoption: this commit came in with the history the project adopted, so no landing records it.

and take the first that exists, if a list of templates is given. --HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 95632c4 · Browse files · 10 files+186 added−27 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

10 files+186 added−27 removed

  • tests:+38 added−1 removed
  • other:+148 added−26 removed

10 files+186 added−27 removed

modified:docs/api.rst+4 added-1 removed
113 unmodified lines
114useful if you want to dig deeper into Jinja2 or :ref:`develop extensions115<jinja-extensions>`.116117.. autoclass:: Environment([options])118 :members: from_string, get_template, join_path, extend, compile_expression118 :members: from_string, get_template, select_template,119 get_or_select_template, join_path, extend, compile_expression120121 .. attribute:: shared122123 If a template was created by using the :class:`Template` constructor
361 unmodified lines
485.. autoexception:: jinja2.UndefinedError486487.. autoexception:: jinja2.TemplateNotFound488489.. autoexception:: jinja2.TemplatesNotFound490491.. autoexception:: jinja2.TemplateSyntaxError492493 .. attribute:: message494
190 unmodified lines
modified:docs/templates.rst+12 added
766 unmodified lines
767 {% include "sidebar.html" ignore missing %}768 {% include "sidebar.html" ignore missing with context %}769 {% include "sidebar.html" ignore missing without context %}770771.. versionadded:: 2.2772773You can also provide a list of templates that are checked for existence774before inclusion. The first template that exists will be included. If775`ignore missing` is given, it will fall back to rendering nothing if776none of the templates exist, otherwise it will raise an exception.777778Example::779780 {% include ['page_detailed.html', 'page.html'] %}781 {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}782783.. _import:784785Import786~~~~~~
472 unmodified lines
modified:jinja2/__init__.py+5 added-4 removed
47 unmodified lines
48from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined4950# exceptions51from jinja2.exceptions import TemplateError, UndefinedError, \52 TemplateNotFound, TemplateSyntaxError, TemplateAssertionError52 TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \53 TemplateAssertionError5455# decorators and public utilities56from jinja2.filters import environmentfilter, contextfilter57from jinja2.utils import Markup, escape, clear_caches, \
4 unmodified lines
62 'PackageLoader', 'DictLoader', 'FunctionLoader', 'PrefixLoader',63 'ChoiceLoader', 'BytecodeCache', 'FileSystemBytecodeCache',64 'MemcachedBytecodeCache', 'Undefined', 'DebugUndefined',65 'StrictUndefined', 'TemplateError', 'UndefinedError', 'TemplateNotFound',65 'TemplateSyntaxError', 'TemplateAssertionError', 'environmentfilter',66 'contextfilter', 'Markup', 'escape', 'environmentfunction',67 'contextfunction', 'clear_caches', 'is_undefined'66 'TemplatesNotFound', 'TemplateSyntaxError', 'TemplateAssertionError',67 'environmentfilter', 'contextfilter', 'Markup', 'escape',68 'environmentfunction', 'contextfunction', 'clear_caches', 'is_undefined'69]
modified:jinja2/compiler.py+11 added-1 removed
888 unmodified lines
889 self.unoptimize_scope(frame)890 if node.ignore_missing:891 self.writeline('try:')892 self.indent()893894 func_name = 'get_or_select_template'895 if isinstance(node.template, nodes.Const):896 if isinstance(node.template.value, basestring):897 func_name = 'get_template'898 elif isinstance(node.template.value, (tuple, list)):899 func_name = 'select_template'900 elif isinstance(node.template, (nodes.Tuple, nodes.List)):901 func_name = 'select_template'902893 self.writeline('template = environment.get_template(', node)903 self.writeline('template = environment.%s(' % func_name, node)904 self.visit(node.template, frame)905 self.write(', %r)' % self.name)906 if node.ignore_missing:907 self.outdent()
643 unmodified lines
modified:jinja2/environment.py+49 added-12 removed
14 unmodified lines
15from jinja2.parser import Parser16from jinja2.optimizer import optimize17from jinja2.compiler import generate18from jinja2.runtime import Undefined, new_context19from jinja2.exceptions import TemplateSyntaxError19from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \20 TemplatesNotFound21from jinja2.utils import import_string, LRUCache, Markup, missing, \22 concat, consume, internalcode2324
501 unmodified lines
526 """527 return template528529 @internalcode530 def _load_template(self, name, globals):531 if self.loader is None:532 raise TypeError('no loader for this environment specified')533 if self.cache is not None:534 template = self.cache.get(name)535 if template is not None and (not self.auto_reload or \536 template.is_up_to_date):537 return template538 template = self.loader.load(self, name, globals)539 if self.cache is not None:540 self.cache[name] = template541 return template542543 @internalcode544 def get_template(self, name, parent=None, globals=None):545 """Load a template from the loader. If a loader is configured this546 method ask the loader for the template and returns a :class:`Template`.547 If the `parent` parameter is not `None`, :meth:`join_path` is called
4 unmodified lines
552553 If the template does not exist a :exc:`TemplateNotFound` exception is554 raised.555 """541 if self.loader is None:542 raise TypeError('no loader for this environment specified')556 if parent is not None:557 name = self.join_path(name, parent)558 return self._load_template(name, self.make_globals(globals))559546 if self.cache is not None:547 template = self.cache.get(name)548 if template is not None and (not self.auto_reload or \549 template.is_up_to_date):550 return template560 @internalcode561 def select_template(self, names, parent=None, globals=None):562 """Works like :meth:`get_template` but tries a number of templates563 before it fails. If it cannot find any of the templates, it will564 raise a :exc:`TemplatesNotFound` exception.565552 template = self.loader.load(self, name, self.make_globals(globals))553 if self.cache is not None:554 self.cache[name] = template555 return template566 .. versionadded:: 2.2567 """568 if not names:569 raise TemplatesNotFound(message=u'Tried to select from an empty list '570 u'of templates.')571 globals = self.make_globals(globals)572 for name in names:573 if parent is not None:574 name = self.join_path(name, parent)575 try:576 return self._load_template(name, globals)577 except TemplateNotFound:578 pass579 raise TemplatesNotFound(names)580581 @internalcode582 def get_or_select_template(self, template_name_or_list,583 parent=None, globals=None):584 """585 Does a typecheck and dispatches to :meth:`select_template` if an586 iterable of template names is given, otherwise to :meth:`get_template`.587588 .. versionadded:: 2.2589 """590 if isinstance(template_name_or_list, basestring):591 return self.get_template(template_name_or_list, parent, globals)592 return self.select_template(template_name_or_list, parent, globals)593594 def from_string(self, source, globals=None, template_class=None):595 """Load a template from a string. This parses the source given and596 returns a :class:`Template` object.597 """
329 unmodified lines
modified:jinja2/exceptions.py+32 added-2 removed
27 unmodified lines
2829class TemplateNotFound(IOError, LookupError, TemplateError):30 """Raised if a template does not exist."""3132 # looks weird, but removes the warning descriptor that just33 # bogusly warns us about message being deprecated34 message = None3532 def __init__(self, name):33 IOError.__init__(self, name)36 def __init__(self, name, message=None):37 IOError.__init__(self)38 if message is None:39 message = name40 self.message = message41 self.name = name42 self.templates = [name]4344 def __unicode__(self):45 return self.message4647 def __str__(self):48 return self.message.encode('utf-8')495051class TemplatesNotFound(TemplateNotFound):52 """Like :class:`TemplateNotFound` but raised if multiple templates53 are selected. This is a subclass of :class:`TemplateNotFound`54 exception, so just catching the base exception will catch both.5556 .. versionadded:: 2.257 """5859 def __init__(self, names=(), message=None):60 if message is None:61 message = u'non of the templates given were found: ' + \62 u', '.join(names)63 TemplateNotFound.__init__(self, names and names[-1] or None, message)64 self.templates = list(names)656667class TemplateSyntaxError(TemplateError):68 """Raised to tell the user that there is a problem with the template."""6970 def __init__(self, message, lineno, name=None, filename=None):
65 unmodified lines
modified:jinja2/meta.py+27 added-2 removed
68 unmodified lines
69 to rebuild parts of the website after a layout template has changed.70 """71 for node in ast.find_all((nodes.Extends, nodes.FromImport, nodes.Import,72 nodes.Include)):73 if isinstance(node.template, nodes.Const) and \74 isinstance(node.template.value, basestring):73 if not isinstance(node.template, nodes.Const):74 # a tuple with some non consts in there75 if isinstance(node.template, (nodes.Tuple, nodes.List)):76 for template_name in node.template.items:77 # something const, only yield the strings and ignore78 # non-string consts that really just make no sense79 if isinstance(template_name, nodes.Const):80 if isinstance(template_name.value, basestring):81 yield template_name.value82 # something dynamic in there83 else:84 yield None85 # something dynamic we don't know about here86 else:87 yield None88 continue89 # constant is a basestring, direct template name90 if isinstance(node.template.value, basestring):91 yield node.template.value92 # a tuple or list (latter *should* not happen) made of consts,93 # yield the consts that are strings. We could warn here for94 # non string values95 elif isinstance(node, nodes.Include) and \96 isinstance(node.template.value, (tuple, list)):97 for template_name in node.template.value:98 if isinstance(template_name, basestring):99 yield template_name100 # something else we don't care about, we could warn here101 else:102 yield None
modified:tests/test_imports.py+19 added-1 removed
5 unmodified lines
6 :copyright: (c) 2009 by the Jinja Team.7 :license: BSD, see LICENSE for more details.8"""9from jinja2 import Environment, DictLoader10from jinja2.exceptions import TemplateNotFound10from jinja2.exceptions import TemplateNotFound, TemplatesNotFound1112from nose.tools import assert_raises1314
28 unmodified lines
43 t = test_env.from_string('{% include "header" without context %}')44 assert t.render(foo=42) == '[|23]'454647def test_choice_includes():48 t = test_env.from_string('{% include ["missing", "header"] %}')49 assert t.render(foo=42) == '[42|23]'5051 t = test_env.from_string('{% include ["missing", "missing2"] ignore missing %}')52 assert t.render(foo=42) == ''5354 t = test_env.from_string('{% include ["missing", "missing2"] %}')55 assert_raises(TemplateNotFound, t.render)56 try:57 t.render()58 except TemplatesNotFound, e:59 assert e.templates == ['missing', 'missing2']60 assert e.name == 'missing2'61 else:62 assert False, 'thou shalt raise'636465def test_include_ignoring_missing():66 t = test_env.from_string('{% include "missing" %}')67 assert_raises(TemplateNotFound, t.render)68 for extra in '', 'with context', 'without context':
47 unmodified lines
modified:tests/test_meta.py+19 added
34 unmodified lines
35 '{% import "meh.html" as meh %}'36 '{% include "muh.html" %}')37 i = meta.find_referenced_templates(ast)38 assert list(i) == ['layout.html', 'test.html', 'meh.html', 'muh.html']394041def test_find_included_templates():42 env = Environment()43 ast = env.parse('{% include ["foo.html", "bar.html"] %}')44 i = meta.find_referenced_templates(ast)45 assert list(i) == ['foo.html', 'bar.html']4647 ast = env.parse('{% include ("foo.html", "bar.html") %}')48 i = meta.find_referenced_templates(ast)49 assert list(i) == ['foo.html', 'bar.html']5051 ast = env.parse('{% include ["foo.html", "bar.html", foo] %}')52 i = meta.find_referenced_templates(ast)53 assert list(i) == ['foo.html', 'bar.html', None]5455 ast = env.parse('{% include ("foo.html", "bar.html", foo) %}')56 i = meta.find_referenced_templates(ast)57 assert list(i) == ['foo.html', 'bar.html', None]
modified:CHANGES+8 added-4 removed
1Jinja2 Changelog2================34Version 2.2.25-------------6(bugfix release, release date to be selected.)4Version 2.35-----------6(codename to be selected, release date to be selected.)78- fixes issue with code generator that causes unbound variables9 to be generated if set was used in if-blocks.9 to be generated if set was used in if-blocks and other small10 identifier problems.11- include tags are now able to select between multiple templates12 and take the first that exists, if a list of templates is13 given.1415Version 2.2.116-------------17(bugfix release, released on September 14th 2009)
114 unmodified lines