Login

A GET string modifier templatetag

Author:
cogat
Posted:
December 11, 2008
Language:
Python
Version:
1.0
Score:
1 (after 3 ratings)

This template tag takes the current GET query, and modifies or adds the value you specify. This is great for GET-query-driven views, where you want to provide URLs which reconfigure the view somehow.

Example Usage:

{% get_string "sort_by" "date" %} returns all=your&current=get&variables=plus&sort_by=date

 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
33
34
35
36
37
38
39
40
"""
requires
TEMPLATE_CONTEXT_PROCESSORS += ('django.core.context_processors.request',)
"""


from django import template
from django.utils.http import urlquote

register = template.Library()

def do_get_string(parser, token):
   try:
       tag_name, key, value = token.split_contents()
#         key = urlquote(key)
#         value = urlquote(value)
   except ValueError:
       return GetStringNode()

   if not (key[0] == key[-1] and key[0] in ('"', "'")):
       raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name

   return GetStringNode(key[1:-1], value)

class GetStringNode(template.Node):
   def __init__(self, key=None, value=None):
       self.key = key
       if value:
           self.value = template.Variable(value)

   def render(self, context):
       get = context.get('request').GET.copy()

       if self.key:
           actual_value = self.value.resolve(context)
           get.__setitem__(self.key, actual_value)

       return get.urlencode()

register.tag('get_string', do_get_string)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.