Created
September 12, 2012 14:40
-
-
Save derek-schaefer/3707073 to your computer and use it in GitHub Desktop.
Django template tag for URL encoding
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
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