Skip to content

Instantly share code, notes, and snippets.

@gavinwahl
Created May 8, 2013 23:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gavinwahl/5544335 to your computer and use it in GitHub Desktop.
Save gavinwahl/5544335 to your computer and use it in GitHub Desktop.
`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 = []
context.push()
for i in self.list.resolve(context):
context[self.var_name] = i
res.append(self.tag.render(context))
context.pop()
return ''.join(res)
@register.tag
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
Copy link
Author

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