Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
`map` template tag
import uuid
from django import template
from django.template.base import Token, TOKEN_BLOCK
register = template.Library()
class MapNode(template.Node):
def __init__(self, var_name, tag, list):
self.var_name = var_name
self.tag = tag
self.list = template.Variable(list)
def render(self, context):
res = []
for i in self.list.resolve(context):
context[self.var_name] = i
return ''.join(res)
def map(parser, token):
_, tag_name, list = token.split_contents()
var_name = uuid.uuid4().hex
fake_token = Token(TOKEN_BLOCK, '%s %s' % (tag_name, var_name))
tag = parser.tags[tag_name](parser, fake_token)
return MapNode(var_name, tag, list)
# {% map include list_of_templates %}
# {# is like ... #}
# {% for template in list_of_templates %}
# {% include template %}
# {% endfor %}

gavinwahl commented May 8, 2013

A map template tag, like the functional map(lambda x: x+1, [1,2,3]) that maps a function across a list. This tag maps a template tag across a list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment