Created
January 29, 2009 08:53
-
-
Save igorgue/54472 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import template # to handle templates variables and context | |
register = template.Library() # register our template tags to be able to use them in our templates | |
from events import models # to get the models of our app | |
class EventMetadataListNode(template.Node): | |
def __init__(self, event_pk, context_var): | |
self.context_var = context_var # new var we are going to create | |
self.event_pk = template.Variable(event_pk) # the pk, get from the template "context" as a variable | |
def render(self, context): | |
# here we create a new context variable named from self.context_var and assign to it the result set | |
# see the use of "resolve" that will get us the var from the context | |
context[self.context_var] = models.EventMetadata.objects.filter(event__pk=self.event_pk.resolve(context)) | |
return '' | |
def do_get_event_metadata(parser, token): | |
""" | |
get the event metadata | |
Example:: | |
{% get_event_metadata event.pk as metadatas %} | |
""" | |
# split the args string, it detects "quoted parameters" and doesn't stop on spaces | |
bits = token.split_contents() | |
if len(bits) != 4: # we check if we passed the right number of args | |
raise template.TemplateSyntaxError(_('%s tag requires exactly 1 argument, and a variable') % bits[0]) | |
return EventMetadataListNode(bits[1], bits[3]) # bits[1] == events.pk, bits[3] == variable | |
# finally we register the new template tag | |
# first parameter is the name in the template the second one is the name in the source file | |
register.tag('get_event_metadata', do_get_event_metadata) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment