uuid template tag

 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
from django.template import Library, Node, TemplateSyntaxError
from uuid import uuid4

register = Library()

class UUIDNode( Node ):
    """
    Implements the logic of this tag.
    """
    def __init__( self, var_name ):
        self.var_name = var_name
        
    def render( self, context ):
        context[ self.var_name ] = str( uuid4() )
        return ''

def do_uuid( parser, token ):
    """
    The purpose of this template tag is to generate a random
    UUID and store it in a named context variable.
    
    Sample usage:
        {% uuid var_name %}
        var_name will contain the generated UUID
    """
    try:
        tag_name, var_name = token.split_contents()
    except ValueError:
        raise TemplateSyntaxError, "%r tag requires exactly one argument" % token.contents.split()[ 0 ]
    return UUIDNode( var_name )

do_uuid = register.tag( 'uuid', do_uuid )

More like this

  1. Randomized Include Tag by justinlilly 4 years, 5 months ago
  2. "Partial Templates" - an alternative to "include" by vigrid 4 years, 3 months ago
  3. Updated - Template context debugger with (I)Pdb by dnordberg 3 years, 9 months ago
  4. Manipulate URL query strings using context variables using a template tag by JHsaunders 2 years, 7 months ago
  5. ifinlist template tag by nomadjourney 4 years, 4 months ago

Comments

(Forgotten your password?)