public
Created

`map` template tag

  • Download Gist
tags.py
Python
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
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 %}

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.