From: Adrian Moennich Date: Sun, 26 Feb 2017 17:00:06 +0000 (+0100) Subject: Add docs for namespace functionality X-Git-Tag: 2.10~24^2~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=cc1d287b2b2d6bcb29201774ff3d6718f8806e4b;p=thirdparty%2Fjinja.git Add docs for namespace functionality --- diff --git a/docs/api.rst b/docs/api.rst index ee88d110..b983e8f0 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -687,6 +687,8 @@ Exceptions unicode strings is that Python 2.x is not using unicode for exceptions and tracebacks as well as the compiler. This will change with Python 3. +.. autoexception:: jinja2.TemplateRuntimeError + .. autoexception:: jinja2.TemplateAssertionError diff --git a/docs/templates.rst b/docs/templates.rst index 5defc8bb..650b55e6 100644 --- a/docs/templates.rst +++ b/docs/templates.rst @@ -908,6 +908,24 @@ Assignments use the `set` tag and can have multiple targets:: did not iterate {% endfor %} + As of version 2.10 more complex use cases can be handled using namespace + objects which allow propagating of changes across scopes:: + + {% set ns = namespace(found=false) %} + {% for item in items %} + {% if item.check_something() %} + {% set ns.found = true %} + {% endif %} + * {{ item.title }} + {% endfor %} + Found item having something: {{ ns.found }} + + Note hat the ``obj.attr`` notation in the `set` tag is only allowed for + namespace objects; attempting to assign an attribute on any other object + will raise an exception. + + .. versionadded:: 2.10 Added support for namespace objects + Block Assignments ~~~~~~~~~~~~~~~~~ @@ -1400,6 +1418,29 @@ The following functions are available in the global scope by default: .. versionadded:: 2.1 +.. class:: namespace(...) + + Creates a new container that allows attribute assignment using the + ``{% set %}`` tag:: + + {% set ns = namespace() %} + {% set ns.foo = 'bar' %} + + The main purpose of this is to allow carrying a value from within a loop + body to an outer scope. Initial values can be provided as a dict, as + keyword arguments, or both (same behavior as Python's `dict` constructor):: + + {% set ns = namespace(found=false) %} + {% for item in items %} + {% if item.check_something() %} + {% set ns.found = true %} + {% endif %} + * {{ item.title }} + {% endfor %} + Found item having something: {{ ns.found }} + + .. versionadded:: 2.10 + Extensions ----------