Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

create {% get_chunk %} templatetag to access a Chunk instance from th…

…e template
  • Loading branch information...
commit 20302fc15b149ba6bec1222c877ca6d61bf4f5ce 1 parent fef8056
@igorsobreira igorsobreira authored
Showing with 103 additions and 14 deletions.
  1. +9 −0 README.md
  2. +41 −10 chunks/templatetags/chunks.py
  3. +53 −4 chunks/tests.py
View
9 README.md
@@ -31,4 +31,13 @@ Well it essentially allows someone to define "chunks" (I had wanted to call it b
</body>
</html>
+if you need the `Chunk` object in the template (maybe you've added some generic relations to it) you should use the `{% get chunk %}` templatetag:
+
+ {% load chunks %}
+
+ {% get_chunk "home_page_left" as chunk_obj %}
+
+ <!-- ... use the Chuck object, then display it's contents -->
+ <div>{{ chuck_obj.content }}</div>
+
This is really helpful in those cases where you want to use `django.contrib.flatpages` but you need multiple content areas. I hope this is helpful to people and I'll be making minor edits as I see them necessary.
View
51 chunks/templatetags/chunks.py
@@ -7,7 +7,7 @@
Chunk = models.get_model('chunks', 'chunk')
CACHE_PREFIX = "chunk_"
-def do_get_chunk(parser, token):
+def do_chunk(parser, token):
# split_contents() knows not to split quoted strings.
tokens = token.split_contents()
if len(tokens) < 2 or len(tokens) > 3:
@@ -17,17 +17,14 @@ def do_get_chunk(parser, token):
cache_time = 0
if len(tokens) == 3:
tag_name, key, cache_time = tokens
- # Check to see if the key is properly double/single quoted
- if not (key[0] == key[-1] and key[0] in ('"', "'")):
- raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
- # Send key without quotes and caching time
- return ChunkNode(key[1:-1], cache_time)
-
+ key = ensure_quoted_string(key, "%r tag's argument should be in quotes" % tag_name)
+ return ChunkNode(key, cache_time)
+
class ChunkNode(template.Node):
def __init__(self, key, cache_time=0):
self.key = key
self.cache_time = cache_time
-
+
def render(self, context):
try:
cache_key = CACHE_PREFIX + self.key
@@ -39,5 +36,39 @@ def render(self, context):
except Chunk.DoesNotExist:
content = ''
return content
-
-register.tag('chunk', do_get_chunk)
+
+
+def do_get_chunk(parser, token):
+ tokens = token.split_contents()
+ if len(tokens) != 4 or tokens[2] != 'as':
+ raise template.TemplateSyntaxError, 'Invalid syntax. Usage: {%% %s "key" as varname %%}' % tokens[0]
+ tagname, key, varname = tokens[0], tokens[1], tokens[3]
+ key = ensure_quoted_string(key, "Key argument to %r must be in quotes" % tagname)
+ return GetChunkNode(key, varname)
+
+class GetChunkNode(template.Node):
+ def __init__(self, key, varname):
+ self.key = key
+ self.varname = varname
+
+ def render(self, context):
+ try:
+ chunk = Chunk.objects.get(key=self.key)
+ except Chunk.DoesNotExist:
+ chunk = None
+ context[self.varname] = chunk
+ return ''
+
+
+def ensure_quoted_string(string, error_message):
+ '''
+ Check to see if the key is properly double/single quoted and
+ returns the string without quotes
+ '''
+ if not (string[0] == string[-1] and string[0] in ('"', "'")):
+ raise template.TemplateSyntaxError, error_message
+ return string[1:-1]
+
+
+register.tag('chunk', do_chunk)
+register.tag('get_chunk', do_get_chunk)
View
57 chunks/tests.py
@@ -4,7 +4,7 @@
from chunks.models import Chunk
-class ChuckTemplateTagTestCase(TestCase):
+class BaseTestCase(TestCase):
def setUp(self):
self.home_page_left = Chunk.objects.create(
@@ -13,6 +13,13 @@ def setUp(self):
cache.delete('cache_home_page_left')
+ def render_template(self, content_string, context={}):
+ template = Template(content_string)
+ return template.render(Context(context))
+
+
+class ChuckTemplateTagTestCase(BaseTestCase):
+
def test_should_render_content_from_key(self):
result = self.render_template('{% load chunks %}'
'<div>{% chunk "home_page_left" %}</div>')
@@ -63,6 +70,48 @@ def test_should_fail_if_key_not_quoted(self):
'{% chunk "home_page_left\' %}')
- def render_template(self, content_string, context={}):
- template = Template(content_string)
- return template.render(Context(context))
+class GetChuckTemplateTagTestCase(BaseTestCase):
+
+ def test_should_get_chunk_object_given_key(self):
+ result = self.render_template('{% load chunks %}'
+ '{% get_chunk "home_page_left" as chunk_obj %}'
+ '<p>{{ chunk_obj.content }}</p>')
+
+ self.assertEquals('<p>This is the content for left box</p>', result)
+
+ def test_should_assign_varname_to_None_if_chunk_not_found(self):
+ result = self.render_template('{% load chunks %}'
+ '{% get_chunk "chunk_not_found" as chunk_obj %}'
+ '{{ chunk_obj }}')
+
+ self.assertEquals('None', result)
+
+ def test_should_fail_if_wrong_number_of_arguments(self):
+ with self.assertRaisesRegexp(TemplateSyntaxError, 'Invalid syntax. Usage: {% get_chunk "key" as varname %}'):
+ self.render_template('{% load chunks %}'
+ '{% get_chunk %}')
+
+ with self.assertRaisesRegexp(TemplateSyntaxError, 'Invalid syntax. Usage: {% get_chunk "key" as varname %}'):
+ self.render_template('{% load chunks %}'
+ '{% get_chunk "home_page_left" %}')
+
+ with self.assertRaisesRegexp(TemplateSyntaxError, 'Invalid syntax. Usage: {% get_chunk "key" as varname %}'):
+ self.render_template('{% load chunks %}'
+ '{% get_chunk "home_page_left" as %}')
+
+ with self.assertRaisesRegexp(TemplateSyntaxError, 'Invalid syntax. Usage: {% get_chunk "key" as varname %}'):
+ self.render_template('{% load chunks %}'
+ '{% get_chunk "home_page_left" notas chunk_obj %}')
+
+ with self.assertRaisesRegexp(TemplateSyntaxError, 'Invalid syntax. Usage: {% get_chunk "key" as varname %}'):
+ self.render_template('{% load chunks %}'
+ '{% get_chunk "home_page_left" as chunk_obj invalid %}')
+
+ def test_should_fail_if_key_not_quoted(self):
+ with self.assertRaisesRegexp(TemplateSyntaxError, "Key argument to u'get_chunk' must be in quotes"):
+ result = self.render_template('{% load chunks %}'
+ '{% get_chunk home_page_left as chunk_obj %}')
+
+ with self.assertRaisesRegexp(TemplateSyntaxError, "Key argument to u'get_chunk' must be in quotes"):
+ result = self.render_template('{% load chunks %}'
+ '{% get_chunk "home_page_left\' as chunk_obj %}')
Please sign in to comment.
Something went wrong with that request. Please try again.