Login

{% with %} template tag

Author:
SmileyChris
Posted:
March 23, 2007
Language:
Python
Version:
.96
Score:
12 (after 12 ratings)

Add a value to the context (inside of this block) for easy access.

Provides a way to stay DRYer in your templates.

NOTE: This tag is now in Django core, so if you have Django >0.96 (or SVN) then you do NOT need this.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# NOTE: This tag is now in Django core, so if you have Django >0.96 (or SVN)
# then you do NOT need this.

from django.template import Library
from django.template import Node, NodeList
from django.template import TemplateSyntaxError

register = Library()

#@register.tag
def do_with(parser, token):
    """
    Add a value to the context (inside of this block) for easy access.

    Example::

        {% with person.addresses.all as addresses %}
            {% if addresses %}
                <h3>Addresses</h3>
                {% for address in addresses %}
                   ...
                {% endfor %}
            {% endif %}
        {% endwith %}
    """
    bits = list(token.split_contents())
    if len(bits) != 4 or bits[2] != "as":
        raise TemplateSyntaxError, "%r expected format is 'value as name'" % tagname
    var = parser.compile_filter(bits[1])
    name = bits[3]
    nodelist = parser.parse(('endwith',))
    parser.delete_first_token()
    return WithNode(var, name, nodelist)
do_with = register.tag('with', do_with)

class WithNode(Node):
    def __init__(self, var, name, nodelist):
        self.var = var
        self.name = name
        self.nodelist = nodelist

    def __repr__(self):
        return "<WithNode>"

    def render(self, context):
        val = self.var.resolve(context)
        context.push()
        context[self.name] = val
        output = self.nodelist.render(context)
        context.pop()
        return output

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Xin (on May 6, 2007):

This tag is more useful, but if I need set more variables this tag use two lines for variables.

For this, I use the tag "set" (-- {% set base_url "../" %} --) (-- {% set obj object %} --). So, when I need change much variable name for an include tag, this save me the half of lines:

{% with category.categories.all as category_list %}
    {% set dir_url "../" %}
    {% set show_user True %}
    {% include "category_list.html" %}
{% endwith %}}

#

Please login first before commenting.