Lets you include another template and pass in named variables. Use like:
{% partial field_template field=form.city %}
If no key is specified, it will use "item" instead. You may pass in multiple variables as comma-separated key=value pairs.
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 | from django import template
from django.template import Library, Node, Variable, loader
from django.template.context import Context
register = template.Library()
def trim(s):
return s.strip()
def stripquotes(s):
if s[0] == s[-1] and s[0] in ('"',"'"):
return s[1:-1]
return s
class PartialTemplateNode(Node):
def __init__(self, template_name, context_vars):
self.template_name = template_name
self.context_vars = dict(zip(context_vars.keys(),
map(Variable, context_vars.values())))
def render(self, context):
template = loader.get_template(self.template_name)
return template.render(Context(dict(zip(self.context_vars.keys(),
map(lambda v: v.resolve(context), self.context_vars.values())))))
@register.tag(name='partial')
def partial_template(parser, token):
bits = token.split_contents()
tag, template, rest = bits[0], trim(stripquotes(bits[1])), ''.join(bits[2:])
pairs = rest.split(',')
context_vars = {}
for pair in pairs:
x = map(stripquotes, map(trim, pair.split('=')))
if len(x) == 1:
context_vars['item'] = x[0]
else:
context_vars[x[0]] = x[1]
return PartialTemplateNode(template, context_vars)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.