Skip to content

Instantly share code, notes, and snippets.

@derek-schaefer
Created September 12, 2012 14:40
Show Gist options
  • Save derek-schaefer/3707073 to your computer and use it in GitHub Desktop.
Save derek-schaefer/3707073 to your computer and use it in GitHub Desktop.
Django template tag for URL encoding
from django.template import Node, Library
import urllib
register = Library()
class URLEncodeNode(Node):
def __init__(self, nodes, plus=False):
self.nodes = nodes
self.plus = plus
def render(self, context):
src = self.nodes.render(context).strip()
if self.plus:
return urllib.quote_plus(src)
return urllib.quote(src)
@register.tag
def urlencode(parser, token):
""" Encodes the contents for safe use as a GET parameter value. """
args = token.contents.split()
nodes = parser.parse(('endurlencode',))
parser.delete_first_token()
return URLEncodeNode(nodes, plus='plus' in args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment