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
Provenance
- Commit
5411ce7- Tree
1665e57- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
fd31049
15 files changed+209 added−28 removed
modified:docs/api.rst+88 added-9 removed
54 unmodified lines55 56 High Level API57 --------------58 59-.. 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, extend61 62 .. attribute:: shared63 64 If a template was created by using the :class:`Template` constructor30 unmodified lines95 For valid object names have a look at :ref:`identifier-naming`.96 97 .. automethod:: overlay([options])98 99+ .. method:: undefined([hint,] [obj,] name[, exc])100 101+ 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.111+112+ The most common way to create an undefined object is by providing113+ a name only::114+115+ return environment.undefined(name='some_name')116+117+ 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::120+121+ if not hasattr(obj, 'attr'):122+ return environment.undefined(obj=obj, name='attr')123+124+ For a more complex example you can provide a hint. For example125+ the :func:`first` filter creates an undefined object that way::126+127+ return environment.undefined('no first item, sequence was empty') 128+129+ 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.133+100-.. autoclass:: jinja2.Template134+.. autoclass:: Template135 :members: make_module, module, new_context136 137 .. attribute:: globals138 5 unmodified lines144 145 The loading name of the template. If the template was loaded from a146 string this is `None`.147 148+ .. attribute:: filename149+150+ The filename of the template on the file system if it was loaded from151+ there. Otherwise this is `None`.152+153 .. automethod:: render([context])154 155 .. automethod:: generate([context])156 6 unmodified lines163 164 .. _identifier-naming:165 166 Notes on Identifiers128-~~~~~~~~~~~~~~~~~~~~167+--------------------168 169 Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to170 match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters171 are currently not allowed. This limitation will probably go away as soon as19 unmodified lines191 192 The closest to regular Python behavior is the `StrictUndefined` which193 disallows all operations beside testing if it's an undefined object.194 156-.. autoclass:: jinja2.runtime.Undefined195+.. autoclass:: jinja2.runtime.Undefined()196 158-.. autoclass:: jinja2.runtime.DebugUndefined197+.. autoclass:: jinja2.runtime.DebugUndefined()198 160-.. autoclass:: jinja2.runtime.StrictUndefined199+.. autoclass:: jinja2.runtime.StrictUndefined()200 201+Undefined objects are created by calling :attr:`undefined`.202 203+204 The Context205 -----------206 207 .. autoclass:: jinja2.runtime.Context()2 unmodified lines210 .. attribute:: parent211 212 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.217 218 .. attribute:: vars219 220 The template local variables. This list contains environment and219 unmodified lines440 context. This is the place where you can put variables and functions441 that should be available all the time. Additionally :attr:`Template.globals`442 exist that are variables available to a specific template that are available443 to all :meth:`~Template.render` calls.444+445+446+Low Level API447+-------------448+449+The low level API exposes functionality that can be useful to understand some450+implementation details, debugging purposes or advanced :ref:`extension451+<jinja-extensions>` techniques.452+453+.. automethod:: Environment.lex454+455+.. automethod:: Environment.parse456+457+.. automethod:: Template.new_context458+459+.. method:: Template.root_render_func(context)460+461+ 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.466+467+ 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.471+472+.. attribute:: Template.blocks473+474+ A dict of block render functions. Each of these functions works exactly475+ like the :meth:`root_render_func` with the same limitations.476+477+.. attribute:: Template.is_up_to_date478+479+ 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 lines4 This page answers some of the often asked questions about Jinja.5 6 .. highlight:: html+jinja7 8-8 Why is it called Jinja?9 -----------------------10 11 The name Jinja was chosen because it's the name of a Japanese temple and7 unmodified lines19 performance of a template depends on many factors and you would have to20 benchmark different engines in different situations. The benchmarks from the21 testsuite show that Jinja2 has a similar performance to `Mako`_ and is more22 than 20 times faster than Django's template engine or Genshi. These numbers24-should be taken with tons of salt!23+should be taken with tons of salt as the benchmarks that took these numbers24+only test a few performance related situations such as looping. They are25+not a good indicator for the templates used in the average application.26+Additionally you should keep in mind that for most web applications27+templates are clearly not the bottleneck.28 29 .. _Mako: http://www.makotemplates.org/30 31 How Compatible is Jinja2 with Django?91 unmodified lines123 If you want to modify the context write a function that returns a variable124 instead that one can assign to a variable by using set::125 126 {% set comments = get_latest_comments() %}127+128+I don't have the _speedups Module. Is Jinja slower now?129+--------------------------------------------------------130+131+To achieve a good performance with automatic escaping enabled the escaping132+function is implemented also written in pure C and used if Jinja2 was133+installed with the speedups module which automatically happens if a C134+compiled is available on the system. It won't affect templates without135+auto escaping much if that feature is not enabled. You may however136+experience werid tracebacks if you are using a Python installation, for137+more information see the next FAQ item.138+139+My tracebacks look weird. What's happening?140+--------------------------------------------141+142+If the speedups module is not compiled and you are using a Python installation143+without ctypes (Python 2.4 without ctypes, Jython or Google's AppEngine)144+Jinja2 is unable to provide correct debugging information and the traceback145+may be incomplete. There is currently no good workaround for Jython or146+the AppEngine as ctypes is unavailable there and it's not possible to use147+the speedups extension.modified:docs/jinjaext.py+1 added-1 removed
46 unmodified lines47 48 Keyword: 'bold #B80000',49 Keyword.Type: '#808080',50 51- Operator.Word: '#333333',51+ Operator.Word: 'bold #B80000',52 53 Name.Builtin: '#333333',54 Name.Function: '#333333',55 Name.Class: 'bold #333333',140 unmodified linesmodified:examples/rwbench/rwbench.py+1 added-1 removed
79 unmodified lines80 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 linesmodified:jinja2/compiler.py+5 added-2 removed
678 unmodified lines679 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 lines783 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 lines1190 self.write(str(val))1191 else:1192 self.write(repr(val))1193 1194+ def visit_TemplateData(self, node, frame):1195+ self.write(repr(node.as_const()))1196+1197 def visit_Tuple(self, node, frame):1198 self.write('(')1199 idx = -11200 for idx, item in enumerate(node.items):185 unmodified linesmodified:jinja2/environment.py+7 added-7 removed
403 unmodified lines404 return cls.from_code(self, self.compile(source), globals, None)405 406 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)411 412 68 unmodified lines481 t.filename = code.co_filename482 t.blocks = namespace['blocks']483 484 # render function and module 485- t._root_render_func = namespace['root']485+ t.root_render_func = namespace['root']486 t._module = None487 488 # debug and loader helpers489 t._debug_info = namespace['debug_info']12 unmodified lines502 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, tb13 unmodified lines524 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, tb534 535 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 lines610 converting it into an unicode- or bytestrings renders the contents.611 """612 613 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.name617 618- __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))620 621 def __str__(self):622 return unicode(self).encode('utf-8')623 66 unmodified linesmodified:jinja2/filters.py+5 added
596 unmodified lines597 """598 return Markup(value)599 600 601+def do_mark_unsafe(value):602+ """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""603+ return unicode(value)604+605+606 def do_reverse(value):607 """Reverse the object or return an iterator the iterates over it the other608 way round.609 """59 unmodified linesmodified:jinja2/nodes.py+10 added
429 unmodified lines430 raise Impossible()431 return cls(value, lineno=lineno, environment=environment)432 433 434+class TemplateData(Literal):435+ """A constant template string."""436+ fields = ('data',)437+438+ def as_const(self):439+ if self.environment.autoescape:440+ return Markup(self.data)441+ return self.data442+443+444 class 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 linesmodified:jinja2/parser.py+2 added-1 removed
721 unmodified lines722 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 linesmodified:jinja2/runtime.py+1 added-1 removed
108 unmodified lines109 return dict((k, self.vars[k]) for k in self.exported_vars)110 111 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)116 117 def call(__self, __obj, *args, **kwargs):329 unmodified linesadded:tests/loaderres/templates/broken.html+3 added
1+Before2+{{ fail() }}3+Afteradded:tests/loaderres/templates/syntaxerror.html+4 added
1+Foo2+{% for item in broken %}3+ ...4+{% endif %}added:tests/test_debug.py+37 added
1+# -*- coding: utf-8 -*-2+"""3+ Test debug interface4+ ~~~~~~~~~~~~~~~~~~~~5+6+ Tests the traceback rewriter.7+8+ :copyright: Copyright 2008 by Armin Ronacher.9+ :license: BSD.10+"""11+from jinja2 import Environment12+from test_loaders import filesystem_loader13+14+15+env = Environment(loader=filesystem_loader)16+17+18+test_runtime_error = '''19+>>> tmpl = MODULE.env.get_template('broken.html')20+>>> tmpl.render(fail=lambda: 1 / 0)21+Traceback (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)26+ZeroDivisionError: integer division or modulo by zero27+'''28+29+30+test_syntax_error = '''31+>>> tmpl = MODULE.env.get_template('syntaxerror.html')32+Traceback (most recent call last):33+ ...34+ File "loaderres/templates/syntaxerror.html", line 4, in <module>35+ {% endif %}36+TemplateSyntaxError: unknown tag 'endif' (syntaxerror.html, line 4)37+'''modified:tests/test_security.py+14 added
4 unmodified lines5 6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9+from jinja2 import Environment10 from jinja2.sandbox import SandboxedEnvironment, \11 ImmutableSandboxedEnvironment, unsafe12 from jinja2 import Markup, escape13 104 unmodified lines118 # escaping and unescaping119 assert escape('"<>&\'') == '"<>&''120 assert Markup("<em>Foo & Bar</em>").striptags() == "Foo & Bar"121 assert Markup("<test>").unescape() == "<test>"122+123+124+def 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 <blink>foo</blink>!</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