Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add a new singular random template tag

Fixes #2
  • Loading branch information...
commit c01f63b2903a7f915d5b514e92e793e2f365119c 1 parent 3a2f040
@paltman paltman authored
Showing with 26 additions and 10 deletions.
  1. +5 −0 docs/usage.rst
  2. +21 −10 marturion/templatetags/marturion_tags.py
View
5 docs/usage.rst
@@ -18,4 +18,9 @@ or::
{% testimonials <number> as quotes %}
+If you just want a single random testimonial you can use::
+
+ {% random_testimonial as quote %}
+
+
To input quotes, you simply add them through the Django admin.
View
31 marturion/templatetags/marturion_tags.py
@@ -11,15 +11,16 @@ class TestimonialsNode(template.Node):
@classmethod
def handle_token(cls, parser, token, order_by, **kwargs):
bits = token.split_contents()
-
- if len(bits) != 4:
- raise template.TemplateSyntaxError("%r takes exactly three arguments "
- "(second argument must be 'as')" % bits[0])
- if bits[2] != "as":
- raise template.TemplateSyntaxError("Second argument to %r must be "
- "'as'" % bits[0])
-
- return cls(parser.compile_filter(bits[1]), bits[3], order_by)
+ if len(bits) == 3:
+ if bits[1] != "as":
+ raise template.TemplateSyntaxError("Second argument to %r must be 'as'" % bits[0])
+ return cls(1, bits[2], order_by)
+ elif len(bits) == 4:
+ if bits[2] != "as":
+ raise template.TemplateSyntaxError("Second argument to %r must be 'as'" % bits[0])
+ return cls(parser.compile_filter(bits[1]), bits[3], order_by)
+ else:
+ raise template.TemplateSyntaxError("Invalid number of arguments for %r " % bits[0])
def __init__(self, how_many, context_var, order_by):
self.how_many = how_many
@@ -27,13 +28,18 @@ def __init__(self, how_many, context_var, order_by):
self.order_by = order_by
def render(self, context):
- how_many = self.how_many.resolve(context)
+ if self.how_many == 1:
+ how_many = 1
+ else:
+ how_many = self.how_many.resolve(context)
context[self.context_var] = list(Testimonial.objects.filter(
active=True
).order_by(
self.order_by
)[:how_many]
)
+ if how_many == 1:
+ context[self.context_var] = context[self.context_var][0]
return u""
@@ -43,5 +49,10 @@ def random_testimonials(parser, token):
@register.tag
+def random_testimonial(parser, token):
+ return TestimonialsNode.handle_token(parser, token, order_by="?")
+
+
+@register.tag
def testimonials(parser, token):
return TestimonialsNode.handle_token(parser, token, order_by="-added")
Please sign in to comment.
Something went wrong with that request. Please try again.