Login

blocksetter

Author:
jerzyk
Posted:
December 10, 2007
Language:
Python
Version:
.96
Tags:
templatetag block set
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. "Magic Link" Management Command by webology 1 month ago
  2. Closest ORM models to a latitude/longitude point by simonw 1 month ago
  3. Log the time taken to execute each DB query by kennyx46 1 month ago
  4. django database snippet by ItsRLuo 1 month ago
  5. Serialize a model instance by chriswedgwood 2 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.