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
Provenance
- Commit
31bbd9e- Tree
f3bbfd8- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
95632c4
10 files changed+186 added−27 removed
modified:docs/api.rst+4 added-1 removed
113 unmodified lines114 useful if you want to dig deeper into Jinja2 or :ref:`develop extensions115 <jinja-extensions>`.116 117 .. 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_expression120 121 .. attribute:: shared122 123 If a template was created by using the :class:`Template` constructor361 unmodified lines485 .. autoexception:: jinja2.UndefinedError486 487 .. autoexception:: jinja2.TemplateNotFound488 489+.. autoexception:: jinja2.TemplatesNotFound490+491 .. autoexception:: jinja2.TemplateSyntaxError492 493 .. attribute:: message494 190 unmodified linesmodified:docs/templates.rst+12 added
766 unmodified lines767 {% include "sidebar.html" ignore missing %}768 {% include "sidebar.html" ignore missing with context %}769 {% include "sidebar.html" ignore missing without context %}770 771+.. versionadded:: 2.2772+773+You can also provide a list of templates that are checked for existence774+before inclusion. The first template that exists will be included. If775+`ignore missing` is given, it will fall back to rendering nothing if776+none of the templates exist, otherwise it will raise an exception.777+778+Example::779+780+ {% include ['page_detailed.html', 'page.html'] %}781+ {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}782+783 .. _import:784 785 Import786 ~~~~~~472 unmodified linesmodified:jinja2/__init__.py+5 added-4 removed
47 unmodified lines48 from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined49 50 # exceptions51 from jinja2.exceptions import TemplateError, UndefinedError, \52- TemplateNotFound, TemplateSyntaxError, TemplateAssertionError52+ TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \53+ TemplateAssertionError54 55 # decorators and public utilities56 from jinja2.filters import environmentfilter, contextfilter57 from jinja2.utils import Markup, escape, clear_caches, \4 unmodified lines62 '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 lines889 self.unoptimize_scope(frame)890 if node.ignore_missing:891 self.writeline('try:')892 self.indent()893+894+ 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'902+893- 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 linesmodified:jinja2/environment.py+49 added-12 removed
14 unmodified lines15 from jinja2.parser import Parser16 from jinja2.optimizer import optimize17 from jinja2.compiler import generate18 from jinja2.runtime import Undefined, new_context19-from jinja2.exceptions import TemplateSyntaxError19+from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \20+ TemplatesNotFound21 from jinja2.utils import import_string, LRUCache, Markup, missing, \22 concat, consume, internalcode23 24 501 unmodified lines526 """527 return template528 529 @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 template542+543+ @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 called4 unmodified lines552 553 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))559 546- 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.565 552- 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)580 581+ @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`.587+588+ .. 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)593+594 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 linesmodified:jinja2/exceptions.py+32 added-2 removed
27 unmodified lines28 29 class TemplateNotFound(IOError, LookupError, TemplateError):30 """Raised if a template does not exist."""31 32+ # looks weird, but removes the warning descriptor that just33+ # bogusly warns us about message being deprecated34+ message = None35+32- 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]43 44+ def __unicode__(self):45+ return self.message46 47+ def __str__(self):48+ return self.message.encode('utf-8')49+50+51+class 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.55+56+ .. versionadded:: 2.257+ """58+59+ 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)65+66+67 class TemplateSyntaxError(TemplateError):68 """Raised to tell the user that there is a problem with the template."""69 70 def __init__(self, message, lineno, name=None, filename=None):65 unmodified linesmodified:jinja2/meta.py+27 added-2 removed
68 unmodified lines69 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 Nonemodified:tests/test_imports.py+19 added-1 removed
5 unmodified lines6 :copyright: (c) 2009 by the Jinja Team.7 :license: BSD, see LICENSE for more details.8 """9 from jinja2 import Environment, DictLoader10-from jinja2.exceptions import TemplateNotFound10+from jinja2.exceptions import TemplateNotFound, TemplatesNotFound11 12 from nose.tools import assert_raises13 14 28 unmodified lines43 t = test_env.from_string('{% include "header" without context %}')44 assert t.render(foo=42) == '[|23]'45 46 47+def test_choice_includes():48+ t = test_env.from_string('{% include ["missing", "header"] %}')49+ assert t.render(foo=42) == '[42|23]'50+51+ t = test_env.from_string('{% include ["missing", "missing2"] ignore missing %}')52+ assert t.render(foo=42) == ''53+54+ 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'63+64+65 def 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 linesmodified:tests/test_meta.py+19 added
34 unmodified lines35 '{% 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']39+40+41+def 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']46+47+ ast = env.parse('{% include ("foo.html", "bar.html") %}')48+ i = meta.find_referenced_templates(ast)49+ assert list(i) == ['foo.html', 'bar.html']50+51+ 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]54+55+ 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
1 Jinja2 Changelog2 ================3 4-Version 2.2.25--------------6-(bugfix release, release date to be selected.)4+Version 2.35+-----------6+(codename to be selected, release date to be selected.)7 8 - 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.14 15 Version 2.2.116 -------------17 (bugfix release, released on September 14th 2009)114 unmodified lines