Sometimes you need to set a little bit more complex variable in the template (e.g. Title), that is being used more than once. this simple tag defines "blockset" tag. {% blockset variable-name %}{%endblockset} everything inside body (between blockset/endblockset) is being assigned to the variable "variable-name".
I have found this quite useful with translations, or setting the title, where you out several variables into one sentence.
Drop me an email if you will find this useful.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class ContextVariableBlockSetter(template.Node):
def __init__(self, variable, nodelist):
self.variable = variable
self.nodelist = nodelist
def render(self, context):
context[self.variable] = self.nodelist.render(context)
return ""
@register.tag
def blockset(parser, node):
bits = node.contents.split()
if len(bits) != 2:
raise template.TemplateSyntaxError, "'%s' tag takes one argument" % bits[0]
nodelist = parser.parse(('endblockset',))
parser.delete_first_token()
return ContextVariableBlockSetter(bits[1], nodelist)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Isn't this what Django's built-in
with
tag already does?#
Please login first before commenting.