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
Provenance
- Commit
9bb7e47- Tree
c3d0fc3- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
d71fff0
16 files changed+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 lines208 }209 210 div.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 }215 216 div.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 }224 224-div.admonition p {225- margin: 0 0 0 40px;225+div.admonition-note {226+ background: url(note.png) no-repeat 10px 40px;227 }228 229+div.admonition-implementation {230+ background: url(implementation.png) no-repeat 10px 40px;231+}232+233 #toc {234 margin: 20px 0 10px 15px;235 padding: 10px;236 width: 200px;63 unmodified lines300 301 dl.function dt,302 dl.class dt,303 dl.exception dt,299-dl.method dt {304+dl.method dt,305+dl.attribute dt {306 font-weight: normal;307 }308 309 dt .descname {38 unmodified linesmodified:docs/api.rst+87 added-5 removed
93 unmodified lines94 95 High Level API96 --------------97 98+The high-level API is the API you will use in the application to load and99+render Jinja2 templates. The :ref:`low-level-api` on the other side is only100+useful if you want to dig deeper into Jinja2 or :ref:`develop extensions101+<jinja-extensions>`.102+103 .. autoclass:: Environment([options])104 :members: from_string, get_template, join_path, extend105 106 .. attribute:: shared68 unmodified lines175 a custom `hint` is provided. This gives undefined objects the176 possibility to enhance the error message.177 178 .. autoclass:: Template174- :members: make_module, module, new_context179+ :members: module, make_module180 181 .. attribute:: globals182 183 The dict with the globals of that template. It's unsafe to modify53 unmodified lines237 disallows all operations beside testing if it's an undefined object.238 239 .. autoclass:: jinja2.runtime.Undefined()240 241+ .. attribute:: _undefined_hint242+243+ Either `None` or an unicode string with the error message for244+ the undefined object.245+246+ .. attribute:: _undefined_obj247+248+ Either `None` or the owner object that caused the undefined object249+ to be created (for example because an attribute does not exist).250+251+ .. attribute:: _undefined_name252+253+ The name for the undefined variable / attribute or just `None`254+ if no such information exists.255+256+ .. attribute:: _undefined_exception257+258+ The exception that the undefined object wants to raise. This259+ is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.260+261+ .. method:: _fail_with_undefined_error(\*args, \**kwargs)262+263+ 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.266+267 .. autoclass:: jinja2.runtime.DebugUndefined()268 269 .. autoclass:: jinja2.runtime.StrictUndefined()270 271 Undefined objects are created by calling :attr:`undefined`.272 273+.. admonition:: Implementation274 275+ :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::280+281+ class NullUndefined(Undefined):282+ def __int__(self):283+ return 0284+ def __float__(self):285+ return 0.0286+287+ 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::293+294+ class NonIterableUndefined(Undefined):295+ __iter__ = Undefined._fail_with_undefined_error296+297+298 The Context299 -----------300 301 .. autoclass:: jinja2.runtime.Context()35 unmodified lines337 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).340 341+ .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)342 343+344+.. admonition:: Implementation345+346+ 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.350+351+ 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.354+355+356 .. _loaders:357 358 Loaders359 -------38 unmodified lines398 .. autofunction:: jinja2.utils.contextfunction399 400 .. function:: escape(s)401 333- 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.406 407+ The return value is a :class:`Markup` string.408+409 .. autofunction:: jinja2.utils.clear_caches410 411+.. autofunction:: jinja2.utils.is_undefined412+413 .. autoclass:: jinja2.utils.Markup414 415 416 Exceptions137 unmodified lines554 exist that are variables available to a specific template that are available555 to all :meth:`~Template.render` calls.556 557 558+.. _low-level-api:559+560 Low Level API561 -------------562 563 The low level API exposes functionality that can be useful to understand some28 unmodified lines592 .. attribute:: Template.is_up_to_date593 594 This attribute is `False` if there is a newer version of the template595 available, otherwise `True`.596+597+.. admonition:: Note598+599+ 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 lines28 29 .. autofunction:: is_internal_attribute30 31 .. autofunction:: modifies_known_mutable32+33+.. admonition:: Note34+35+ 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.40+41+ 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.44+45+ 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 lines173 {% else %}174 hmm. {{ user.username|e }} looks pretty normal175 {% endif %}176 177+Loops178+~~~~~179 180+For loops work very similar to Django, the only incompatibility is that in181+Jinja2 the special variable for the loop context is called `loop` and not182+`forloop` like in Django.183+184+185 Mako186 ----187 188 .. highlight:: html+mako33 unmodified linesmodified:docs/templates.rst+23 added-13 removed
145 unmodified lines146 147 This will yield all elements without whitespace between them. If `seq` was148 a list of numbers from ``1`` to ``9`` the output would be ``123456789``.149 150-Note that you must not use a whitespace between the tag and the minus sign:150+If :ref:`line-statements` are enabled they strip leading whitespace151+automatically up to the beginning of the line.152 152- valid::153+.. admonition:: Note154 155+ You must not use a whitespace between the tag and the minus sign.156+157+ **valid**::158+159 {%- if foo -%}...{% endif %}160 156- invalid::161+ **invalid**::162 163 {% - if foo - %}...{% endif %}164 160-If :ref:`line-statements` are enabled they strip leading whitespace161-automatically up to the beginning of the line.165 163-166 Escaping167 --------168 169 It is sometimes desirable or even necessary to have Jinja ignore parts it628 unmodified lines798 templates, they are useful in some rare cases such as the :func:`xmlattr`799 filter.800 801 true / 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.803 804+.. admonition:: Note805+806+ 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.812+813 Math814 ~~~~815 816 Jinja allows you to calculate with values. This is rarely useful in templates46 unmodified lines863 864 (expr)865 group an expression.866 857-Note that there is no support for any bit operations or something similar.867+.. admonition:: Note868 859-- 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).``873 874 875 Other Operators876 ~~~~~~~~~~~~~~~199 unmodified linesmodified:ext/jinja.el+3 added-3 removed
41 unmodified lines42 ;; 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 linesmodified:jinja2/__init__.py+2 added-2 removed
48 unmodified lines49 50 # decorators and public utilities51 from jinja2.filters import environmentfilter, contextfilter52 from jinja2.utils import Markup, escape, clear_caches, \53- environmentfunction, contextfunction53+ environmentfunction, contextfunction, is_undefined54 55 __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 lines186 187 static 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 linesmodified:jinja2/filters.py+6 added-5 removed
21 unmodified lines22 _word_re = re.compile(r'\w+')23 24 25 def 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 f33 34 35 def 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 = True535 unmodified lines577 578 579 class _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))583 584 def __new__(cls, (key, value)):585 return tuple.__new__(cls, (key, list(value)))586 105 unmodified linesmodified:jinja2/nodes.py+2 added-1 removed
398 unmodified lines399 """400 fields = ('name', 'ctx')401 402 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')405 406 407 class Literal(Expr):408 """Baseclass for literals."""382 unmodified linesmodified:jinja2/parser.py+4 added-3 removed
452 unmodified lines453 454 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 linesmodified:jinja2/runtime.py+39 added-27 removed
115 unmodified lines116 """117 return dict(self.parent, **self.vars)118 119 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 lines164 self.name165 )166 167 168+# register the context as mutable mapping if possible169+try:170+ from collections import MutableMapping171+ MutableMapping.register(Context)172+except ImportError:173+ pass174+175+176 class TemplateReference(object):177 """The `self` in templates."""178 179 def __init__(self, context):153 unmodified lines333 self.name is None and 'anonymous' or repr(self.name)334 )335 336 324-def 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)344-345-337 class 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 lines356 self._undefined_obj = obj357 self._undefined_name = name358 self._undefined_exception = exc359 360+ 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)380+381 __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_error386 387 def __str__(self):388 return self.__unicode__().encode('utf-8')389 378- def __repr__(self):379- return 'Undefined'380-390 def __unicode__(self):391 return u''392 393 def __len__(self):5 unmodified lines399 400 def __nonzero__(self):401 return False402 403+ def __repr__(self):404+ return 'Undefined'405 406+407 class DebugUndefined(Undefined):408 """An undefined that returns the debug info when printed.409 410 >>> foo = DebugUndefined(name='foo')39 unmodified lines450 jinja2.exceptions.UndefinedError: 'foo' is undefined451 """452 __slots__ = ()453 __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \442- fail_with_undefined_error454+ Undefined._fail_with_undefined_error455 456 457 # 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 linemodified:jinja2/utils.py+38 added-6 removed
61 unmodified lines62 del _test_gen_bug, _error63 64 65 def 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::72+73+ @contextcallable74+ def get_exported_names(context):75+ return sorted(context.exported_vars)76 """77 f.contextfunction = True78 return f79 80 81 def 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 f89 90 91+def 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::97+98+ def default(var, default=''):99+ if is_undefined(var):100+ return default101+ return var102+ """103+ from jinja2.runtime import Undefined104+ return isinstance(obj, Undefined)105+106+107 def 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 are444 unmodified lines555 556 __copy__ = copy557 558 559+# register the LRU cache as mutable mapping if possible560+try:561+ from collections import MutableMapping562+ MutableMapping.register(LRUCache)563+except ImportError:564+ pass565+566+567 # we have to import it down here as the speedups module imports the568 # markup type which is define above.569 try:570 from jinja2._speedups import escape, soft_unicode37 unmodified linesmodified:tests/test_syntax.py+8 added
161 unmodified lines162 163 def test_block_end_name(env):164 env.from_string('{% block foo %}...{% endblock foo %}')165 raises(TemplateSyntaxError, env.from_string, '{% block x %}{% endblock y %}')166+167+168+def 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)