# 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 %}

Addresses

{% 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 "" def render(self, context): val = self.var.resolve(context) context.push() context[self.name] = val output = self.nodelist.render(context) context.pop() return output