Skip to content
Myr

even more tests, fixed severe bug with autoescaping.

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 fd31049 · Browse files · 15 files+209 added−28 removed
This commit

State

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

Diff stats

15 files+209 added−28 removed

  • tests:+58 added−0 removed
  • other:+151 added−28 removed

15 files+209 added−28 removed

modified:docs/api.rst+88 added-9 removed
54 unmodified lines
5556High Level API57--------------5859.. autoclass:: jinja2.environment.Environment([options])60 :members: from_string, get_template, join_path, parse, lex, extend59.. autoclass:: Environment([options])60 :members: from_string, get_template, join_path, extend6162 .. attribute:: shared6364 If a template was created by using the :class:`Template` constructor
30 unmodified lines
95 For valid object names have a look at :ref:`identifier-naming`.9697 .. automethod:: overlay([options])9899 .. method:: undefined([hint,] [obj,] name[, exc])100101 Creates a new :class:`Undefined` object for `name`. This is useful102 for filters or functions that may return undefined objects for103 some operations. All parameters except of `hint` should be provided104 as keyword parameters for better readability. The `hint` is used as105 error message for the exception if provided, otherwise the error106 message generated from `obj` and `name` automatically. The exception107 provided as `exc` is raised if something with the generated undefined108 object is done that the undefined object does not allow. The default109 exception is :exc:`UndefinedError`. If a `hint` is provided the110 `name` may be ommited.111112 The most common way to create an undefined object is by providing113 a name only::114115 return environment.undefined(name='some_name')116117 This means that the name `some_name` is not defined. If the name118 was from an attribute of an object it makes sense to tell the119 undefined object the holder object to improve the error message::120121 if not hasattr(obj, 'attr'):122 return environment.undefined(obj=obj, name='attr')123124 For a more complex example you can provide a hint. For example125 the :func:`first` filter creates an undefined object that way::126127 return environment.undefined('no first item, sequence was empty') 128129 If it the `name` or `obj` is known (for example because an attribute130 was accessed) it shold be passed to the undefined object, even if131 a custom `hint` is provided. This gives undefined objects the132 possibility to enhance the error message.133100.. autoclass:: jinja2.Template134.. autoclass:: Template135 :members: make_module, module, new_context136137 .. attribute:: globals138
5 unmodified lines
144145 The loading name of the template. If the template was loaded from a146 string this is `None`.147148 .. attribute:: filename149150 The filename of the template on the file system if it was loaded from151 there. Otherwise this is `None`.152153 .. automethod:: render([context])154155 .. automethod:: generate([context])156
6 unmodified lines
163164.. _identifier-naming:165166Notes on Identifiers128~~~~~~~~~~~~~~~~~~~~167--------------------168169Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to170match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters171are currently not allowed. This limitation will probably go away as soon as
19 unmodified lines
191192The closest to regular Python behavior is the `StrictUndefined` which193disallows all operations beside testing if it's an undefined object.194156.. autoclass:: jinja2.runtime.Undefined195.. autoclass:: jinja2.runtime.Undefined()196158.. autoclass:: jinja2.runtime.DebugUndefined197.. autoclass:: jinja2.runtime.DebugUndefined()198160.. autoclass:: jinja2.runtime.StrictUndefined199.. autoclass:: jinja2.runtime.StrictUndefined()200201Undefined objects are created by calling :attr:`undefined`.202203204The Context205-----------206207.. autoclass:: jinja2.runtime.Context()
2 unmodified lines
210 .. attribute:: parent211212 A dict of read only, global variables the template looks up. These213 can either come from another :class:`Context`, from the173 :attr:`Environment.globals` or :attr:`Template.globals`. It must not174 be altered.214 :attr:`Environment.globals` or :attr:`Template.globals` or points215 to a dict created by combining the globals with the variables216 passed to the render function. It must not be altered.217218 .. attribute:: vars219220 The template local variables. This list contains environment and
219 unmodified lines
440context. This is the place where you can put variables and functions441that should be available all the time. Additionally :attr:`Template.globals`442exist that are variables available to a specific template that are available443to all :meth:`~Template.render` calls.444445446Low Level API447-------------448449The low level API exposes functionality that can be useful to understand some450implementation details, debugging purposes or advanced :ref:`extension451<jinja-extensions>` techniques.452453.. automethod:: Environment.lex454455.. automethod:: Environment.parse456457.. automethod:: Template.new_context458459.. method:: Template.root_render_func(context)460461 This is the low level render function. It's passed a :class:`Context`462 that has to be created by :meth:`new_context` of the same template or463 a compatible template. This render function is generated by the464 compiler from the template code and returns a generator that yields465 unicode strings.466467 If an exception in the template code happens the template engine will468 not rewrite the exception but pass through the original one. As a469 matter of fact this function should only be called from within a470 :meth:`render` / :meth:`generate` / :meth:`stream` call.471472.. attribute:: Template.blocks473474 A dict of block render functions. Each of these functions works exactly475 like the :meth:`root_render_func` with the same limitations.476477.. attribute:: Template.is_up_to_date478479 This attribute is `False` if there is a newer version of the template480 available, otherwise `True`.
modified:docs/faq.rst+26 added-2 removed
3 unmodified lines
4This page answers some of the often asked questions about Jinja.56.. highlight:: html+jinja788Why is it called Jinja?9-----------------------1011The name Jinja was chosen because it's the name of a Japanese temple and
7 unmodified lines
19performance of a template depends on many factors and you would have to20benchmark different engines in different situations. The benchmarks from the21testsuite show that Jinja2 has a similar performance to `Mako`_ and is more22than 20 times faster than Django's template engine or Genshi. These numbers24should be taken with tons of salt!23should be taken with tons of salt as the benchmarks that took these numbers24only test a few performance related situations such as looping. They are25not a good indicator for the templates used in the average application.26Additionally you should keep in mind that for most web applications27templates are clearly not the bottleneck.2829.. _Mako: http://www.makotemplates.org/3031How Compatible is Jinja2 with Django?
91 unmodified lines
123If you want to modify the context write a function that returns a variable124instead that one can assign to a variable by using set::125126 {% set comments = get_latest_comments() %}127128I don't have the _speedups Module. Is Jinja slower now?129--------------------------------------------------------130131To achieve a good performance with automatic escaping enabled the escaping132function is implemented also written in pure C and used if Jinja2 was133installed with the speedups module which automatically happens if a C134compiled is available on the system. It won't affect templates without135auto escaping much if that feature is not enabled. You may however136experience werid tracebacks if you are using a Python installation, for137more information see the next FAQ item.138139My tracebacks look weird. What's happening?140--------------------------------------------141142If the speedups module is not compiled and you are using a Python installation143without ctypes (Python 2.4 without ctypes, Jython or Google's AppEngine)144Jinja2 is unable to provide correct debugging information and the traceback145may be incomplete. There is currently no good workaround for Jython or146the AppEngine as ctypes is unavailable there and it's not possible to use147the speedups extension.
modified:docs/jinjaext.py+1 added-1 removed
46 unmodified lines
4748 Keyword: 'bold #B80000',49 Keyword.Type: '#808080',5051 Operator.Word: '#333333',51 Operator.Word: 'bold #B80000',5253 Name.Builtin: '#333333',54 Name.Function: '#333333',55 Name.Class: 'bold #333333',
140 unmodified lines
modified:examples/rwbench/rwbench.py+1 added-1 removed
79 unmodified lines
80 t = Timer(setup='from __main__ import test_%s as bench' % test,81 stmt='bench()')82 sys.stdout.write(' >> %-20s<running>' % test)83 sys.stdout.flush()84 sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=50) / 50))84 sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=200) / 200))
modified:jinja2/_speedups.c+5 added-4 removed
1/**2 * jinja2._speedups3 * ~~~~~~~~~~~~~~~~4 *5 * This module implements a few functions in C for better performance. It6 * also defines a `tb_set_next` function that is used to patch the debug7 * traceback. If the speedups module is not compiled a ctypes implementation8 * is used.5 * This module implements functions for automatic escaping in C for better6 * performance. Additionally it defines a `tb_set_next` function to patch the7 * debug traceback. If the speedups module is not compiled a ctypes8 * implementation of `tb_set_next` and Python implementations of the other9 * functions are used.10 *11 * :copyright: 2008 by Armin Ronacher, Mickaël Guérin.12 * :license: BSD.13 */
200 unmodified lines
modified:jinja2/compiler.py+5 added-2 removed
678 unmodified lines
679 self.indent()680 self.writeline('if parent_template is not None:')681 self.indent()682 self.writeline('for event in parent_template.'683 '_root_render_func(context):')683 'root_render_func(context):')684 self.indent()685 self.writeline('yield event')686 self.outdent(2 + (not self.has_known_extends))687
95 unmodified lines
783 if node.with_context:784 self.writeline('template = environment.get_template(', node)785 self.visit(node.template, frame)786 self.write(', %r)' % self.name)787 self.writeline('for event in template._root_render_func('787 self.writeline('for event in template.root_render_func('788 'template.new_context(context.parent, True)):')789 else:790 self.writeline('for event in environment.get_template(', node)791 self.visit(node.template, frame)
398 unmodified lines
1190 self.write(str(val))1191 else:1192 self.write(repr(val))11931194 def visit_TemplateData(self, node, frame):1195 self.write(repr(node.as_const()))11961197 def visit_Tuple(self, node, frame):1198 self.write('(')1199 idx = -11200 for idx, item in enumerate(node.items):
185 unmodified lines
modified:jinja2/environment.py+7 added-7 removed
403 unmodified lines
404 return cls.from_code(self, self.compile(source), globals, None)405406 def make_globals(self, d):407 """Return a dict for the globals."""408 if d is None:408 if not d:409 return self.globals410 return dict(self.globals, **d)411412
68 unmodified lines
481 t.filename = code.co_filename482 t.blocks = namespace['blocks']483484 # render function and module 485 t._root_render_func = namespace['root']485 t.root_render_func = namespace['root']486 t._module = None487488 # debug and loader helpers489 t._debug_info = namespace['debug_info']
12 unmodified lines
502 This will return the rendered template as unicode string.503 """504 vars = dict(*args, **kwargs)505 try:506 return concat(self._root_render_func(self.new_context(vars)))506 return concat(self.root_render_func(self.new_context(vars)))507 except:508 from jinja2.debug import translate_exception509 exc_type, exc_value, tb = translate_exception(sys.exc_info())510 raise exc_type, exc_value, tb
13 unmodified lines
524 It accepts the same arguments as :meth:`render`.525 """526 vars = dict(*args, **kwargs)527 try:528 for event in self._root_render_func(self.new_context(vars)):528 for event in self.root_render_func(self.new_context(vars)):529 yield event530 except:531 from jinja2.debug import translate_exception532 exc_type, exc_value, tb = translate_exception(sys.exc_info())533 raise exc_type, exc_value, tb534535 def new_context(self, vars=None, shared=False):536 """Create a new template context for this template. The vars536 """Create a new :class:`Context` for this template. The vars537 provided will be passed to the template. Per default the globals538 are added to the context, if shared is set to `True` the data539 provided is used as parent namespace. This is used to share the540 same globals in multiple contexts without consuming more memory.
69 unmodified lines
610 converting it into an unicode- or bytestrings renders the contents.611 """612613 def __init__(self, template, context):614 self._body_stream = list(template._root_render_func(context))614 self._body_stream = list(template.root_render_func(context))615 self.__dict__.update(context.get_exported())616 self.__name__ = template.name617618 __html__ = lambda x: Markup(concat(x._body_stream))618 __unicode__ = lambda x: concat(x._body_stream)619 __html__ = lambda x: Markup(concat(x._body_stream))620621 def __str__(self):622 return unicode(self).encode('utf-8')623
66 unmodified lines
modified:jinja2/filters.py+5 added
596 unmodified lines
597 """598 return Markup(value)599600601def do_mark_unsafe(value):602 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""603 return unicode(value)604605606def do_reverse(value):607 """Reverse the object or return an iterator the iterates over it the other608 way round.609 """
59 unmodified lines
modified:jinja2/nodes.py+10 added
429 unmodified lines
430 raise Impossible()431 return cls(value, lineno=lineno, environment=environment)432433434class TemplateData(Literal):435 """A constant template string."""436 fields = ('data',)437438 def as_const(self):439 if self.environment.autoescape:440 return Markup(self.data)441 return self.data442443444class Tuple(Literal):445 """For loop unpacking and some other things like multiple arguments446 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple447 is used for loading the names or storing.
342 unmodified lines
modified:jinja2/parser.py+2 added-1 removed
721 unmodified lines
722 while self.stream:723 token = self.stream.current724 if token.type is 'data':725 if token.value:726 add_data(nodes.Const(token.value, lineno=token.lineno))726 add_data(nodes.TemplateData(token.value,727 lineno=token.lineno))728 self.stream.next()729 elif token.type is 'variable_begin':730 self.stream.next()731 add_data(self.parse_tuple(with_condexpr=True))
24 unmodified lines
modified:jinja2/runtime.py+1 added-1 removed
108 unmodified lines
109 return dict((k, self.vars[k]) for k in self.exported_vars)110111 def get_all(self):112 """Return a copy of the complete context as dict including the113 global variables.113 exported variables.114 """115 return dict(self.parent, **self.vars)116117 def call(__self, __obj, *args, **kwargs):
329 unmodified lines
added:tests/loaderres/templates/broken.html+3 added
1Before2{{ fail() }}3After
added:tests/loaderres/templates/syntaxerror.html+4 added
1Foo2{% for item in broken %}3 ...4{% endif %}
added:tests/test_debug.py+37 added
1# -*- coding: utf-8 -*-2"""3 Test debug interface4 ~~~~~~~~~~~~~~~~~~~~56 Tests the traceback rewriter.78 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10"""11from jinja2 import Environment12from test_loaders import filesystem_loader131415env = Environment(loader=filesystem_loader)161718test_runtime_error = '''19>>> tmpl = MODULE.env.get_template('broken.html')20>>> tmpl.render(fail=lambda: 1 / 0)21Traceback (most recent call last):22 File "loaderres/templates/broken.html", line 2, in top-level template code23 {{ fail() }}24 File "<doctest test_runtime_error[1]>", line 1, in <lambda>25 tmpl.render(fail=lambda: 1 / 0)26ZeroDivisionError: integer division or modulo by zero27'''282930test_syntax_error = '''31>>> tmpl = MODULE.env.get_template('syntaxerror.html')32Traceback (most recent call last):33 ...34 File "loaderres/templates/syntaxerror.html", line 4, in <module>35 {% endif %}36TemplateSyntaxError: unknown tag 'endif' (syntaxerror.html, line 4)37'''
modified:tests/test_security.py+14 added
4 unmodified lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja2 import Environment10from jinja2.sandbox import SandboxedEnvironment, \11 ImmutableSandboxedEnvironment, unsafe12from jinja2 import Markup, escape13
104 unmodified lines
118 # escaping and unescaping119 assert escape('"<>&\'') == '&#34;&lt;&gt;&amp;&#39;'120 assert Markup("<em>Foo &amp; Bar</em>").striptags() == "Foo & Bar"121 assert Markup("&lt;test&gt;").unescape() == "<test>"122123124def test_template_data():125 env = Environment(autoescape=True)126 t = env.from_string('{% macro say_hello(name) %}'127 '<p>Hello {{ name }}!</p>{% endmacro %}'128 '{{ say_hello("<blink>foo</blink>") }}')129 escaped_out = '<p>Hello &lt;blink&gt;foo&lt;/blink&gt;!</p>'130 assert t.render() == escaped_out131 assert unicode(t.module) == escaped_out132 assert escape(t.module) == escaped_out133 assert t.module.say_hello('<blink>foo</blink>') == escaped_out134 assert escape(t.module.say_hello('<blink>foo</blink>')) == escaped_out