Skip to content
Myr

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.

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 d71fff0 · Browse files · 16 files+249 added−74 removed
This commit

State

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

Diff stats

16 files+249 added−74 removed

  • tests:+8 added−0 removed
  • other:+241 added−74 removed

16 files+249 added−74 removed

added:docs/_static/implementation.pngbinary

A binary file, added.

added:docs/_static/note.pngbinary

A binary file, added.

modified:docs/_static/style.css+14 added-8 removed
207 unmodified lines
208}209210div.admonition {211 margin: 10px 0 10px 0;212 padding: 10px;212 padding: 10px 10px 10px 60px;213 border: 1px solid #ccc;214 background-color: #f8f8f8;214}215216div.admonition p.admonition-title {218 margin: -3px 0 5px 0;217 background-color: #b41717;218 color: white;219 margin: -10px -10px 10px -60px;220 padding: 4px 10px 4px 10px;221 font-weight: bold;220 color: #b41717;221 font-size: 16px;222 font-size: 15px;223}224224div.admonition p {225 margin: 0 0 0 40px;225div.admonition-note {226 background: url(note.png) no-repeat 10px 40px;227}228229div.admonition-implementation {230 background: url(implementation.png) no-repeat 10px 40px;231}232233#toc {234 margin: 20px 0 10px 15px;235 padding: 10px;236 width: 200px;
63 unmodified lines
300301dl.function dt,302dl.class dt,303dl.exception dt,299dl.method dt {304dl.method dt,305dl.attribute dt {306 font-weight: normal;307}308309dt .descname {
38 unmodified lines
modified:docs/api.rst+87 added-5 removed
93 unmodified lines
9495High Level API96--------------9798The high-level API is the API you will use in the application to load and99render Jinja2 templates. The :ref:`low-level-api` on the other side is only100useful if you want to dig deeper into Jinja2 or :ref:`develop extensions101<jinja-extensions>`.102103.. autoclass:: Environment([options])104 :members: from_string, get_template, join_path, extend105106 .. attribute:: shared
68 unmodified lines
175 a custom `hint` is provided. This gives undefined objects the176 possibility to enhance the error message.177178.. autoclass:: Template174 :members: make_module, module, new_context179 :members: module, make_module180181 .. attribute:: globals182183 The dict with the globals of that template. It's unsafe to modify
53 unmodified lines
237disallows all operations beside testing if it's an undefined object.238239.. autoclass:: jinja2.runtime.Undefined()240241 .. attribute:: _undefined_hint242243 Either `None` or an unicode string with the error message for244 the undefined object.245246 .. attribute:: _undefined_obj247248 Either `None` or the owner object that caused the undefined object249 to be created (for example because an attribute does not exist).250251 .. attribute:: _undefined_name252253 The name for the undefined variable / attribute or just `None`254 if no such information exists.255256 .. attribute:: _undefined_exception257258 The exception that the undefined object wants to raise. This259 is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.260261 .. method:: _fail_with_undefined_error(\*args, \**kwargs)262263 When called with any arguments this method raises264 :attr:`_undefined_exception` with an error message generated265 from the undefined hints stored on the undefined object.266267.. autoclass:: jinja2.runtime.DebugUndefined()268269.. autoclass:: jinja2.runtime.StrictUndefined()270271Undefined objects are created by calling :attr:`undefined`.272273.. admonition:: Implementation274275 :class:`Undefined` objects are implemented by overriding the special276 `__underscore__` methods. For example the default :class:`Undefined`277 class implements `__unicode__` in a way that it returns an empty278 string, however `__int__` and others still fail with an exception. To279 allow conversion to int by returning ``0`` you can implement your own::280281 class NullUndefined(Undefined):282 def __int__(self):283 return 0284 def __float__(self):285 return 0.0286287 To disallow a method, just override it and raise288 :attr:`_undefined_exception`. Because this is a very common idom in289 undefined objects there is the helper method290 :meth:`_fail_with_undefined_error`. That does that automatically. Here291 a class that works like the regular :class:`UndefinedError` but chokes292 on iteration::293294 class NonIterableUndefined(Undefined):295 __iter__ = Undefined._fail_with_undefined_error296297298The Context299-----------300301.. autoclass:: jinja2.runtime.Context()
35 unmodified lines
337 in this dict are the names of the blocks, and the values a list of338 blocks registered. The last item in each list is the current active339 block (latest in the inheritance chain).340341 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)342343344.. admonition:: Implementation345346 Context is immutable for the same reason Python's frame locals are347 immutable inside functions. Both Jinja2 and Python are not using the348 context / frame locals as data storage for variables but only as primary349 data source.350351 When a template accesses a variable the template does not define, Jinja2352 looks up the variable in the context, after that the variable is treated353 as if it was defined in the template.354355356.. _loaders:357358Loaders359-------
38 unmodified lines
398.. autofunction:: jinja2.utils.contextfunction399400.. function:: escape(s)401333 Convert the characters &, <, >, and " in string s to HTML-safe sequences.334 Use this if you need to display text that might contain such characters335 in HTML. This function will not escaped objects that do have an HTML336 representation such as already escaped data.402 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`403 to HTML-safe sequences. Use this if you need to display text that might404 contain such characters in HTML. This function will not escaped objects405 that do have an HTML representation such as already escaped data.406407 The return value is a :class:`Markup` string.408409.. autofunction:: jinja2.utils.clear_caches410411.. autofunction:: jinja2.utils.is_undefined412413.. autoclass:: jinja2.utils.Markup414415416Exceptions
137 unmodified lines
554exist that are variables available to a specific template that are available555to all :meth:`~Template.render` calls.556557558.. _low-level-api:559560Low Level API561-------------562563The low level API exposes functionality that can be useful to understand some
28 unmodified lines
592.. attribute:: Template.is_up_to_date593594 This attribute is `False` if there is a newer version of the template595 available, otherwise `True`.596597.. admonition:: Note598599 The low-level API is fragile. Future Jinja2 versions will not change it600 in a backwards incompatible way but modifications in the Jinja core may601 shine through. For example if Jinja2 introduces a new AST node in later602 versions that may be returned by :meth:`~Environment.parse`.
modified:docs/sandbox.rst+15 added
27 unmodified lines
2829.. autofunction:: is_internal_attribute3031.. autofunction:: modifies_known_mutable3233.. admonition:: Note3435 The Jinja2 sandbox alone is no solution for perfect security. Especially36 for web applications you have to keep in mind that users may create37 templates with arbitrary HTML in so it's crucial to ensure that (if you38 are running multiple users on the same server) they can't harm each other39 via JavaScript insertions and much more.4041 Also the sandbox is only as good as the configuration. We stronly42 recommend only passing non-shared resources to the template and use43 some sort of whitelisting for attributes.4445 Also keep in mind that templates may raise runtime or compile time errors,46 so make sure to catch them.
modified:docs/switching.rst+7 added
172 unmodified lines
173 {% else %}174 hmm. {{ user.username|e }} looks pretty normal175 {% endif %}176177Loops178~~~~~179180For loops work very similar to Django, the only incompatibility is that in181Jinja2 the special variable for the loop context is called `loop` and not182`forloop` like in Django.183184185Mako186----187188.. highlight:: html+mako
33 unmodified lines
modified:docs/templates.rst+23 added-13 removed
145 unmodified lines
146 147This will yield all elements without whitespace between them. If `seq` was148a list of numbers from ``1`` to ``9`` the output would be ``123456789``.149150Note that you must not use a whitespace between the tag and the minus sign:150If :ref:`line-statements` are enabled they strip leading whitespace151automatically up to the beginning of the line.152152 valid::153.. admonition:: Note154155 You must not use a whitespace between the tag and the minus sign.156157 **valid**::158159 {%- if foo -%}...{% endif %}160156 invalid::161 **invalid**::162163 {% - if foo - %}...{% endif %}164160If :ref:`line-statements` are enabled they strip leading whitespace161automatically up to the beginning of the line.165163166Escaping167--------168169It is sometimes desirable or even necessary to have Jinja ignore parts it
628 unmodified lines
798 templates, they are useful in some rare cases such as the :func:`xmlattr`799 filter.800801true / false:800 true is always true and false is always false. Keep in mind that those801 literals are lowercase!802 true is always true and false is always false.803804.. admonition:: Note805806 The special constants `true`, `false` and `none` are indeed lowercase.807 Because that caused confusion in the past, when writing `True` expands808 to an undefined variable that is considered false, all three of them can809 be written in title case too (`True`, `False`, and `None`). However for810 consistency (all Jinja identifiers are lowercase) you should use the811 lowercase versions.812813Math814~~~~815816Jinja allows you to calculate with values. This is rarely useful in templates
46 unmodified lines
863864(expr)865 group an expression.866857Note that there is no support for any bit operations or something similar.867.. admonition:: Note868859- special note regarding ``not``: The ``is`` and ``in`` operators support860 negation using an infix notation too: ``foo is not bar`` and861 ``foo not in bar`` instead of ``not foo is bar`` and ``not foo in bar``.862 All other expressions require a prefix notation: ``not (foo and bar).``869 The ``is`` and ``in`` operators support negation using an infix notation870 too: ``foo is not bar`` and ``foo not in bar`` instead of ``not foo is bar``871 and ``not foo in bar``. All other expressions require a prefix notation:872 ``not (foo and bar).``873874875Other Operators876~~~~~~~~~~~~~~~
199 unmodified lines
modified:ext/jinja.el+3 added-3 removed
41 unmodified lines
42 ;; variables43 '("\\({{ ?\\)\\([^|]*?\\)\\(|.*?\\)? ?}}" . (1 font-lock-variable-name-face))44 ;; keywords and builtins45 (cons (rx word-start46 (or "in" "as" "reversed" "recursive" "not" "and" "or"47 "if" "else" "import" "with" "without" "context")46 (or "in" "as" "recursive" "not" "and" "or" "if" "else"47 "import" "with" "without" "context")48 word-end)49 font-lock-keyword-face)50 (cons (rx word-start51 (or "true" "false" "null" "loop" "block" "super" "forloop")51 (or "true" "false" "none" "loop" "self" "super")52 word-end)53 font-lock-builtin-face)54 ;; tests55 '("\\(is\\)[ \t]*\\(not\\)[ \t]*\\([a-zA-Z_]+\\)"
157 unmodified lines
modified:jinja2/__init__.py+2 added-2 removed
48 unmodified lines
4950# decorators and public utilities51from jinja2.filters import environmentfilter, contextfilter52from jinja2.utils import Markup, escape, clear_caches, \53 environmentfunction, contextfunction53 environmentfunction, contextfunction, is_undefined5455__all__ = [56 'Environment', 'Template', 'BaseLoader', 'FileSystemLoader',57 'PackageLoader', 'DictLoader', 'FunctionLoader', 'PrefixLoader',58 'ChoiceLoader', 'Undefined', 'DebugUndefined', 'StrictUndefined',59 'TemplateError', 'UndefinedError', 'TemplateNotFound',60 'TemplateSyntaxError', 'TemplateAssertionError', 'environmentfilter',61 'contextfilter', 'Markup', 'escape', 'environmentfunction',62 'contextfunction', 'clear_caches'62 'contextfunction', 'clear_caches', 'is_undefined'63]
modified:jinja2/_speedups.c+1 added-1 removed
185 unmodified lines
186187static PyMethodDef module_methods[] = {188 {"escape", (PyCFunction)escape, METH_O,189 "escape(s) -> markup\n\n"190 "Convert the characters &, <, >, and \" in string s to HTML-safe\n"190 "Convert the characters &, <, >, ', and \" in string s to HTML-safe\n"191 "sequences. Use this if you need to display text that might contain\n"192 "such characters in HTML. Marks return value as markup string."},193 {"soft_unicode", (PyCFunction)soft_unicode, METH_O,194 "soft_unicode(object) -> string\n\n"
19 unmodified lines
modified:jinja2/filters.py+6 added-5 removed
21 unmodified lines
22_word_re = re.compile(r'\w+')232425def contextfilter(f):26 """Decorator for marking context dependent filters. The current context27 argument will be passed as first argument.26 """Decorator for marking context dependent filters. The current27 :class:`Context` will be passed as first argument.28 """29 if getattr(f, 'environmentfilter', False):30 raise TypeError('filter already marked as environment filter')31 f.contextfilter = True32 return f333435def environmentfilter(f):36 """Decorator for marking evironment dependent filters. The environment37 used for the template is passed to the filter as first argument.36 """Decorator for marking evironment dependent filters. The current37 :class:`Environment` is passed to the filter as first argument.38 """39 if getattr(f, 'contextfilter', False):40 raise TypeError('filter already marked as context filter')41 f.environmentfilter = True
535 unmodified lines
577578579class _GroupTuple(tuple):580 __slots__ = ()581 grouper, list = (property(itemgetter(x)) for x in xrange(2))581 grouper = property(itemgetter(0))582 list = property(itemgetter(1))583584 def __new__(cls, (key, value)):585 return tuple.__new__(cls, (key, list(value)))586
105 unmodified lines
modified:jinja2/nodes.py+2 added-1 removed
398 unmodified lines
399 """400 fields = ('name', 'ctx')401402 def can_assign(self):403 return self.name not in ('true', 'false', 'none')403 return self.name not in ('true', 'false', 'none',404 'True', 'False', 'None')405406407class Literal(Expr):408 """Baseclass for literals."""
382 unmodified lines
modified:jinja2/parser.py+4 added-3 removed
452 unmodified lines
453454 def parse_primary(self, with_postfix=True):455 token = self.stream.current456 if token.type is 'name':457 if token.value in ('true', 'false'):458 node = nodes.Const(token.value == 'true', lineno=token.lineno)459 elif token.value == 'none':457 if token.value in ('true', 'false', 'True', 'False'):458 node = nodes.Const(token.value in ('true', 'True'),459 lineno=token.lineno)460 elif token.value in ('none', 'None'):461 node = nodes.Const(None, lineno=token.lineno)462 else:463 node = nodes.Name(token.value, 'load', lineno=token.lineno)464 self.stream.next()
292 unmodified lines
modified:jinja2/runtime.py+39 added-27 removed
115 unmodified lines
116 """117 return dict(self.parent, **self.vars)118119 def call(__self, __obj, *args, **kwargs):120 """Call the callable with the arguments and keyword arguments121 provided but inject the active context or environment as first122 argument if the callable is a :func:`contextfunction` or123 :func:`environmentfunction`.124 """125 if __debug__:126 __traceback_hide__ = True127 if isinstance(__obj, _context_function_types):128 if getattr(__obj, 'contextfunction', 0):
35 unmodified lines
164 self.name165 )166167168# register the context as mutable mapping if possible169try:170 from collections import MutableMapping171 MutableMapping.register(Context)172except ImportError:173 pass174175176class TemplateReference(object):177 """The `self` in templates."""178179 def __init__(self, context):
153 unmodified lines
333 self.name is None and 'anonymous' or repr(self.name)334 )335336324def fail_with_undefined_error(self, *args, **kwargs):325 """Regular callback function for undefined objects that raises an326 `UndefinedError` on call.327 """328 if self._undefined_hint is None:329 if self._undefined_obj is None:330 hint = '%r is undefined' % self._undefined_name331 elif not isinstance(self._undefined_name, basestring):332 hint = '%r object has no element %r' % (333 self._undefined_obj.__class__.__name__,334 self._undefined_name335 )336 else:337 hint = '%r object has no attribute %r' % (338 self._undefined_obj.__class__.__name__,339 self._undefined_name340 )341 else:342 hint = self._undefined_hint343 raise self._undefined_exception(hint)344345337class Undefined(object):338 """The default undefined type. This undefined type can be printed and339 iterated over, but every other access will raise an :exc:`UndefinedError`:340
15 unmodified lines
356 self._undefined_obj = obj357 self._undefined_name = name358 self._undefined_exception = exc359360 def _fail_with_undefined_error(self, *args, **kwargs):361 """Regular callback function for undefined objects that raises an362 `UndefinedError` on call.363 """364 if self._undefined_hint is None:365 if self._undefined_obj is None:366 hint = '%r is undefined' % self._undefined_name367 elif not isinstance(self._undefined_name, basestring):368 hint = '%r object has no element %r' % (369 self._undefined_obj.__class__.__name__,370 self._undefined_name371 )372 else:373 hint = '%r object has no attribute %r' % (374 self._undefined_obj.__class__.__name__,375 self._undefined_name376 )377 else:378 hint = self._undefined_hint379 raise self._undefined_exception(hint)380381 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \382 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \383 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \384 __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \373 fail_with_undefined_error385 __int__ = __float__ = __complex__ = _fail_with_undefined_error386387 def __str__(self):388 return self.__unicode__().encode('utf-8')389378 def __repr__(self):379 return 'Undefined'380390 def __unicode__(self):391 return u''392393 def __len__(self):
5 unmodified lines
399400 def __nonzero__(self):401 return False402403 def __repr__(self):404 return 'Undefined'405406407class DebugUndefined(Undefined):408 """An undefined that returns the debug info when printed.409410 >>> foo = DebugUndefined(name='foo')
39 unmodified lines
450 jinja2.exceptions.UndefinedError: 'foo' is undefined451 """452 __slots__ = ()453 __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \442 fail_with_undefined_error454 Undefined._fail_with_undefined_error455456457# remove remaining slots attributes, after the metaclass did the magic they458# are unneeded and irritating as they contain wrong data for the subclasses.
1 unmodified line
modified:jinja2/utils.py+38 added-6 removed
61 unmodified lines
62 del _test_gen_bug, _error636465def contextfunction(f):66 """This decorator can be used to mark a callable as context callable. A67 context callable is passed the active context as first argument when68 called from the template.66 """This decorator can be used to mark a function or method context callable.67 A context callable is passed the active :class:`Context` as first argument when68 called from the template. This is useful if a function wants to get access69 to the context or functions provided on the context object. For example70 a function that returns a sorted list of template variables the current71 template exports could look like this::7273 @contextcallable74 def get_exported_names(context):75 return sorted(context.exported_vars)76 """77 f.contextfunction = True78 return f798081def environmentfunction(f):75 """This decorator can be used to mark a callable as environment callable.76 A environment callable is passed the current environment as first argument77 when called from the template.82 """This decorator can be used to mark a function or method as environment83 callable. This decorator works exactly like the :func:`contextfunction`84 decorator just that the first argument is the active :class:`Environment`85 and not context.86 """87 f.environmentfunction = True88 return f899091def is_undefined(obj):92 """Check if the object passed is undefined. This does nothing more than93 performing an instance check against :class:`Undefined` but looks nicer.94 This can be used for custom filters or tests that want to react to95 undefined variables. For example a custom default filter can look like96 this::9798 def default(var, default=''):99 if is_undefined(var):100 return default101 return var102 """103 from jinja2.runtime import Undefined104 return isinstance(obj, Undefined)105106107def clear_caches():108 """Jinja2 keeps internal caches for environments and lexers. These are109 used so that Jinja2 doesn't have to recreate environments and lexers all110 the time. Normally you don't have to care about that but if you are
444 unmodified lines
555556 __copy__ = copy557558559# register the LRU cache as mutable mapping if possible560try:561 from collections import MutableMapping562 MutableMapping.register(LRUCache)563except ImportError:564 pass565566567# we have to import it down here as the speedups module imports the568# markup type which is define above.569try:570 from jinja2._speedups import escape, soft_unicode
37 unmodified lines
modified:tests/test_syntax.py+8 added
161 unmodified lines
162163def test_block_end_name(env):164 env.from_string('{% block foo %}...{% endblock foo %}')165 raises(TemplateSyntaxError, env.from_string, '{% block x %}{% endblock y %}')166167168def test_contant_casing(env):169 for const in True, False, None:170 tmpl = env.from_string('{{ %s }}|{{ %s }}|{{ %s }}' % (171 str(const), str(const).lower(), str(const).upper()172 ))173 assert tmpl.render() == '%s|%s|' % (const, const)