]> git.ipfire.org Git - thirdparty/jinja.git/commitdiff
Add docs for namespace functionality
authorAdrian Moennich <adrian@planetcoding.net>
Sun, 26 Feb 2017 17:00:06 +0000 (18:00 +0100)
committerAdrian Moennich <adrian@planetcoding.net>
Sat, 24 Jun 2017 08:56:54 +0000 (10:56 +0200)
docs/api.rst
docs/templates.rst

index ee88d110a042d7ba86d9c787bd75fe685e4d76c2..b983e8f05f2fbecab3f5fc2a0e7997db81d68326 100644 (file)
@@ -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
 
 
index 5defc8bb6f36e4214c1d8db1e08e79d0fef9862a..650b55e63a649b804011c404d716ae9528219e11 100644 (file)
@@ -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
 ----------