Login

blocksetter

Author:
jerzyk
Posted:
December 10, 2007
Language:
Python
Version:
.96
Score:
1 (after 3 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

ubernostrum (on December 10, 2007):

Isn't this what Django's built-in with tag already does?

#

Please login first before commenting.