Skip to content
Myr

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

11 files+115 added−14 removed

modified:docs/api.rst+2 added-2 removed
107 unmodified lines
108109 .. automethod:: stream([context])110111112.. autoclass:: jinja2.environment.TemplateStream112.. autoclass:: jinja2.environment.TemplateStream()113 :members: disable_buffering, enable_buffering114115116.. _identifier-naming:
36 unmodified lines
153154The Context155-----------156157.. autoclass:: jinja2.runtime.Context157.. autoclass:: jinja2.runtime.Context()158 :members: resolve, get_exported, get_all159160 .. attribute:: parent161
210 unmodified lines
modified:docs/extensions.rst+16 added-5 removed
90 unmodified lines
91.. _gettext: http://docs.python.org/dev/library/gettext92.. _Babel: http://babel.edgewall.org/939495do96~~95Expression Statement96--------------------9798**Import name:** `jinja2.ext.do`99100The do aka expression-statement extension adds a simple `do` tag to the100The "do" aka expression-statement extension adds a simple `do` tag to the101template engine that works like a variable expression but ignores the102return value.103104.. _loopcontrols-extension:105106loopcontrols107~~~~~~~~~~~~106Loop Controls107-------------108109**Import name:** `jinja2.ext.loopcontrols`110111This extension adds support for `break` and `continue` in loops. After
36 unmodified lines
148149 env = Environment(extensions=[FragmentCacheExtension])150 env.fragment_cache = SimpleCache()151152Inside the template it's then possible to mark blocks as cacheable. The153following example caches a sidebar for 300 seconds:154155.. sourcecode:: html+jinja156157 {% cache 'sidebar', 300 %}158 <div class="sidebar">159 ...160 </div>161 {% endcache %}162163.. _Werkzeug: http://werkzeug.pocoo.org/164165Extension API166~~~~~~~~~~~~~
83 unmodified lines
modified:jinja2/compiler.py+6 added-3 removed
676 unmodified lines
677 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()688689 # make sure that the parent root is called.
673 unmodified lines
1363 def visit_EnvironmentAttribute(self, node, frame):1364 self.write('environment.' + node.name)13651366 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))13681369 def visit_ImportedName(self, node, frame):1370 self.write(self.import_aliases[node.importname])13711372 def visit_InternalName(self, node, frame):1373 self.write(node.name)13741375 def visit_ContextReference(self, node, frame):1376 self.write('context')13771378 def visit_Continue(self, node, frame):1379 self.writeline('continue', node)13801381 def visit_Break(self, node, frame):
1 unmodified line
modified:jinja2/nodes.py+5 added-1 removed
765 unmodified lines
766767 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')771772773class ImportedName(Expr):774 """If created with an import name the import name is returned on node
25 unmodified lines
800 def as_const(self):801 return Markup(self.expr.as_const())802803804class ContextReference(Expr):805 """Returns the current template context."""806807808class Continue(Stmt):809 """Continue a loop."""810811
8 unmodified lines
modified:jinja2/optimizer.py+4 added
32 unmodified lines
33 self.environment = environment3435 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 lines
modified:jinja2/runtime.py+1 added-1 removed
161 unmodified lines
162 def __init__(self, context):163 self.__context = context164165 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 = name
273 unmodified lines
modified:tests/test_ext.py+32 added-1 removed
4 unmodified lines
56 :copyright: 2008 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja2 import Environment9from jinja2 import Environment, nodes10from jinja2.ext import Extension111213importable_object = 23141516class TestExtension(Extension):17 tags = set(['test'])18 ext_attr = 421920 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)2728 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 )353637def test_loop_controls():38 env = Environment(extensions=['jinja2.ext.loopcontrols'])3940 tmpl = env.from_string('''
18 unmodified lines
59 {%- for char in "foo" %}60 {%- do items.append(loop.index0 ~ char) %}61 {%- endfor %}{{ items|join(', ') }}''')62 assert tmpl.render() == '0f, 1o, 2o'636465def 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 lines
34LOOPERROR1 = '''\35{% for item in [1] if loop.index == 0 %}...{% endfor %}'''36LOOPERROR2 = '''\37{% for item in [] %}...{% else %}{{ loop }}{% endfor %}'''38LOOPFILTER = '''\39{% for item in range(10) if item is even %}[{{ item }}]{% endfor %}'''40EXTENDEDLOOPFILTER = '''\41{% for item in range(10) if item is even %}[{{ loop.index42}}:{{ item }}]{% endfor %}'''434445def test_simple(env):46 tmpl = env.from_string(SIMPLE)
71 unmodified lines
118 tmpl = env.from_string(LOOPERROR1)119 raises(UndefinedError, tmpl.render)120 tmpl = env.from_string(LOOPERROR2)121 assert tmpl.render() == ''122123124def 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 lines
3031def test_empty(env):32 tmpl = env.from_string(EMPTY)33 assert tmpl.render() == '[]'343536def 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'404142def 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 lines
9798def test_reuse_blocks(env):99 tmpl = env.from_string('{{ self.foo() }}|{% block foo %}42{% endblock %}|{{ self.foo() }}')100 assert tmpl.render() == '42|42|42'101102103def 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 lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja2.sandbox import SandboxedEnvironment, unsafe9from jinja2.sandbox import SandboxedEnvironment, \10 ImmutableSandboxedEnvironment, unsafe111213class PrivateStuff(object):14
53 unmodified lines
68Traceback (most recent call last):69 ...70TemplateSyntaxError: expected token 'in', got '.' (line 1)71'''727374test_immutable_environment = '''75>>> env = MODULE.ImmutableSandboxedEnvironment()76>>> env.from_string('{{ [].append(23) }}').render()77Traceback (most recent call last):78 ...79SecurityError: access to attribute 'append' of 'list' object is unsafe.80>>> env.from_string('{{ {1:2}.clear() }}').render()81Traceback (most recent call last):82 ...83SecurityError: access to attribute 'clear' of 'dict' object is unsafe.84'''