more unittests and updated documentation for extensions. Fixed bug in optimizer that caused blocks to be optimized away under some circumstances.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent 3da9031 · Browse files · 11 files·+115 added−14 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+115 added−14 removed
- tests:+81 added−2 removed
- other:+34 added−12 removed
Provenance
- Commit
6df604e- Tree
6b8f1e7- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
3da9031
11 files changed+115 added−14 removed
modified:docs/api.rst+2 added-2 removed
107 unmodified lines108 109 .. automethod:: stream([context])110 111 112-.. autoclass:: jinja2.environment.TemplateStream112+.. autoclass:: jinja2.environment.TemplateStream()113 :members: disable_buffering, enable_buffering114 115 116 .. _identifier-naming:36 unmodified lines153 154 The Context155 -----------156 157-.. autoclass:: jinja2.runtime.Context157+.. autoclass:: jinja2.runtime.Context()158 :members: resolve, get_exported, get_all159 160 .. attribute:: parent161 210 unmodified linesmodified:docs/extensions.rst+16 added-5 removed
90 unmodified lines91 .. _gettext: http://docs.python.org/dev/library/gettext92 .. _Babel: http://babel.edgewall.org/93 94 95-do96-~~95+Expression Statement96+--------------------97 98 **Import name:** `jinja2.ext.do`99 100-The do aka expression-statement extension adds a simple `do` tag to the100+The "do" aka expression-statement extension adds a simple `do` tag to the101 template engine that works like a variable expression but ignores the102 return value.103 104 .. _loopcontrols-extension:105 106-loopcontrols107-~~~~~~~~~~~~106+Loop Controls107+-------------108 109 **Import name:** `jinja2.ext.loopcontrols`110 111 This extension adds support for `break` and `continue` in loops. After36 unmodified lines148 149 env = Environment(extensions=[FragmentCacheExtension])150 env.fragment_cache = SimpleCache()151 152+Inside the template it's then possible to mark blocks as cacheable. The153+following example caches a sidebar for 300 seconds:154+155+.. sourcecode:: html+jinja156+157+ {% cache 'sidebar', 300 %}158+ <div class="sidebar">159+ ...160+ </div>161+ {% endcache %}162+163 .. _Werkzeug: http://werkzeug.pocoo.org/164 165 Extension API166 ~~~~~~~~~~~~~83 unmodified linesmodified:jinja2/compiler.py+6 added-3 removed
676 unmodified lines677 frame.toplevel = frame.rootlevel = True678 self.indent()679 if have_extends:680 self.writeline('parent_template = None')681- self.pull_locals(frame)682- self.pull_dependencies(node.body)681 if 'self' in find_undeclared(node.body, ('self',)):682 frame.identifiers.add_special('self')683 self.writeline('l_self = TemplateReference(context)')684+ self.pull_locals(frame)685+ self.pull_dependencies(node.body)686 self.blockvisit(node.body, frame)687 self.outdent()688 689 # make sure that the parent root is called.673 unmodified lines1363 def visit_EnvironmentAttribute(self, node, frame):1364 self.write('environment.' + node.name)1365 1366 def visit_ExtensionAttribute(self, node, frame):1367- self.write('environment.extensions[%r].%s' % (node.identifier, node.attr))1367+ self.write('environment.extensions[%r].%s' % (node.identifier, node.name))1368 1369 def visit_ImportedName(self, node, frame):1370 self.write(self.import_aliases[node.importname])1371 1372 def visit_InternalName(self, node, frame):1373 self.write(node.name)1374 1375+ def visit_ContextReference(self, node, frame):1376+ self.write('context')1377+1378 def visit_Continue(self, node, frame):1379 self.writeline('continue', node)1380 1381 def visit_Break(self, node, frame):1 unmodified linemodified:jinja2/nodes.py+5 added-1 removed
765 unmodified lines766 767 This node is usually constructed by calling the768 :meth:`~jinja2.ext.Extension.attr` method on an extension.769 """770- fields = ('identifier', 'attr')770+ fields = ('identifier', 'name')771 772 773 class ImportedName(Expr):774 """If created with an import name the import name is returned on node25 unmodified lines800 def as_const(self):801 return Markup(self.expr.as_const())802 803 804+class ContextReference(Expr):805+ """Returns the current template context."""806+807+808 class Continue(Stmt):809 """Continue a loop."""810 811 8 unmodified linesmodified:jinja2/optimizer.py+4 added
32 unmodified lines33 self.environment = environment34 35 def visit_If(self, node):36 """Eliminate dead code."""37+ # do not optimize ifs that have a block inside so that it doesn't38+ # break super().39+ if node.find(nodes.Block) is not None:40+ return self.generic_visit(node)41 try:42 val = self.visit(node.test).as_const()43 except nodes.Impossible:44 return self.generic_visit(node)24 unmodified linesmodified:jinja2/runtime.py+1 added-1 removed
161 unmodified lines162 def __init__(self, context):163 self.__context = context164 165 def __getitem__(self, name):166- func = self.__context.blocks[name][-1]166+ func = self.__context.blocks[name][0]167 wrap = self.__context.environment.autoescape and \168 Markup or (lambda x: x)169 render = lambda: wrap(concat(func(self.__context)))170 render.__name__ = render.name = name273 unmodified linesmodified:tests/test_ext.py+32 added-1 removed
4 unmodified lines5 6 :copyright: 2008 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9-from jinja2 import Environment9+from jinja2 import Environment, nodes10+from jinja2.ext import Extension11 12 13+importable_object = 2314+15+16+class TestExtension(Extension):17+ tags = set(['test'])18+ ext_attr = 4219+20+ def parse(self, parser):21+ return nodes.Output([self.call_method('_dump', [22+ nodes.EnvironmentAttribute('sandboxed'),23+ self.attr('ext_attr'),24+ nodes.ImportedName(__name__ + '.importable_object'),25+ nodes.ContextReference()26+ ])]).set_lineno(parser.stream.next().lineno)27+28+ def _dump(self, sandboxed, ext_attr, imported_object, context):29+ return '%s|%s|%s|%s' % (30+ sandboxed,31+ ext_attr,32+ imported_object,33+ context.blocks34+ )35+36+37 def test_loop_controls():38 env = Environment(extensions=['jinja2.ext.loopcontrols'])39 40 tmpl = env.from_string('''18 unmodified lines59 {%- for char in "foo" %}60 {%- do items.append(loop.index0 ~ char) %}61 {%- endfor %}{{ items|join(', ') }}''')62 assert tmpl.render() == '0f, 1o, 2o'63+64+65+def test_extension_nodes():66+ env = Environment(extensions=[TestExtension])67+ tmpl = env.from_string('{% test %}')68+ assert tmpl.render() == 'False|42|23|{}'modified:tests/test_forloop.py+12 added
33 unmodified lines34 LOOPERROR1 = '''\35 {% for item in [1] if loop.index == 0 %}...{% endfor %}'''36 LOOPERROR2 = '''\37 {% for item in [] %}...{% else %}{{ loop }}{% endfor %}'''38+LOOPFILTER = '''\39+{% for item in range(10) if item is even %}[{{ item }}]{% endfor %}'''40+EXTENDEDLOOPFILTER = '''\41+{% for item in range(10) if item is even %}[{{ loop.index42+}}:{{ item }}]{% endfor %}'''43 44 45 def test_simple(env):46 tmpl = env.from_string(SIMPLE)71 unmodified lines118 tmpl = env.from_string(LOOPERROR1)119 raises(UndefinedError, tmpl.render)120 tmpl = env.from_string(LOOPERROR2)121 assert tmpl.render() == ''122+123+124+def test_loop_filter(env):125+ tmpl = env.from_string(LOOPFILTER)126+ assert tmpl.render() == '[0][2][4][6][8]'127+ tmpl = env.from_string(EXTENDEDLOOPFILTER)128+ assert tmpl.render() == '[1:0][2:2][3:4][4:6][5:8]'modified:tests/test_ifcondition.py+13 added
29 unmodified lines30 31 def test_empty(env):32 tmpl = env.from_string(EMPTY)33 assert tmpl.render() == '[]'34+35+36+def test_complete(env):37+ tmpl = env.from_string('{% if a %}A{% elif b %}B{% elif c == d %}'38+ 'C{% else %}D{% endif %}')39+ assert tmpl.render(a=0, b=False, c=42, d=42.0) == 'C'40+41+42+def test_no_scope(env):43+ tmpl = env.from_string('{% if a %}{% set foo = 1 %}{% endif %}{{ foo }}')44+ assert tmpl.render(a=True) == '1'45+ tmpl = env.from_string('{% if true %}{% set foo = 1 %}{% endif %}{{ foo }}')46+ assert tmpl.render() == '1'modified:tests/test_inheritance.py+9 added
96 unmodified lines97 98 def test_reuse_blocks(env):99 tmpl = env.from_string('{{ self.foo() }}|{% block foo %}42{% endblock %}|{{ self.foo() }}')100 assert tmpl.render() == '42|42|42'101+102+103+def test_preserve_blocks():104+ env = Environment(loader=DictLoader({105+ 'a': '{% if false %}{% block x %}A{% endblock %}{% endif %}{{ self.x() }}',106+ 'b': '{% extends "a" %}{% block x %}B{{ super() }}{% endblock %}'107+ }))108+ tmpl = env.get_template('b')109+ assert tmpl.render() == 'BA'modified:tests/test_security.py+15 added-1 removed
4 unmodified lines5 6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9-from jinja2.sandbox import SandboxedEnvironment, unsafe9+from jinja2.sandbox import SandboxedEnvironment, \10+ ImmutableSandboxedEnvironment, unsafe11 12 13 class PrivateStuff(object):14 53 unmodified lines68 Traceback (most recent call last):69 ...70 TemplateSyntaxError: expected token 'in', got '.' (line 1)71 '''72+73+74+test_immutable_environment = '''75+>>> env = MODULE.ImmutableSandboxedEnvironment()76+>>> env.from_string('{{ [].append(23) }}').render()77+Traceback (most recent call last):78+ ...79+SecurityError: access to attribute 'append' of 'list' object is unsafe.80+>>> env.from_string('{{ {1:2}.clear() }}').render()81+Traceback (most recent call last):82+ ...83+SecurityError: access to attribute 'clear' of 'dict' object is unsafe.84+'''