Login

uuid template tag

Author:
nomadjourney
Posted:
March 7, 2009
Language:
Python
Version:
1.0
Tags:
template-tag uuid
Score:
3 (after 3 ratings)

A simple template tag that generates a random UUID and stores it in a name context variable.

 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. UUIDField by bwhittington 5 years, 11 months ago
  2. autogenerated UUID model field by kedar 1 year ago
  3. "If in" template tag by andrew 6 years, 11 months ago
  4. uuid model field by newspire 6 years, 3 months ago
  5. UUIDField by trbs 7 years, 8 months ago

Comments

Please login first before commenting.