forked from ericholscher/django-test-utils
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add some hotness to the parse_ttags function. Now allows you to pass …
…a custom list of things to parse, much nicer.
- Loading branch information
1 parent
7db8f10
commit 27844c3
Showing
1 changed file
with
31 additions
and
10 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,48 @@ | ||
from django import template | ||
from django import template | ||
|
||
register = template.Library() | ||
def parse_ttag(token, possible_tags=['as', 'for', 'limit', 'exclude']): | ||
""" | ||
A function to parse a template tag. | ||
Pass in the token to parse, and a list of keywords to look for. | ||
It sets the name of the tag to 'tag_name' in the hash returned. | ||
Default list of keywords is:: | ||
['as', 'for', 'limit', 'exclude'] | ||
>>> from django.template import Token, TOKEN_TEXT | ||
>>> from test_utils.templatetags.utils import parse_ttag | ||
>>> parse_ttag('super_cool_tag for my_object as bob', ['as']) | ||
{'tag_name': u'super_cool_tag', u'as': u'bob'} | ||
>>> parse_ttag('super_cool_tag for my_object as bob', ['as', 'for']) | ||
{'tag_name': u'super_cool_tag', u'as': u'bob', u'for': u'my_object'} | ||
""" | ||
|
||
def parse_ttag(token): | ||
bits = token.split_contents() | ||
tags = {} | ||
possible_tags = ['as', 'for', 'limit', 'exclude'] | ||
if isinstance(token, template.Token): | ||
bits = token.split_contents() | ||
else: | ||
bits = token.split(' ') | ||
tags = {'tag_name': bits.pop(0)} | ||
for index, bit in enumerate(bits): | ||
if bit.strip() in possible_tags: | ||
tags[bit.strip()] = bits[index+1] | ||
if len(bits) != index-1: | ||
tags[bit.strip()] = bits[index+1] | ||
return tags | ||
|
||
def context_for_object(token, Node): | ||
"""This is a function that returns a Node. | ||
""" | ||
Example Usage | ||
This is a function that returns a Node. | ||
It takes a string from a template tag in the format | ||
TagName for [object] as [context variable] | ||
""" | ||
tags = parse_ttag(token) | ||
tags = parse_ttag(token, ['for', 'as']) | ||
if len(tags) == 2: | ||
return Node(tags['for'], tags['as']) | ||
elif len(tags) == 1: | ||
return Node(tags['for']) | ||
else: | ||
#raise template.TemplateSyntaxError, "%s: Fail" % bits[] | ||
print "ERROR" | ||
|