- Author:
- johan-de-taeye
- Posted:
- August 9, 2007
- Language:
- Python
- Version:
- .96
- Score:
- 3 (after 11 ratings)
Often a page contains a link to itself, with an additional parameter for in the url. E.g. to sort the page in a different way, to export the data into another format, etc... This tag makes this easy, avoiding any hardcoded urls in your pages.
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 | Example usage in html template:
<a href="{% addurlparameter sort 1 %}">Sort on field 1</a>
<a href="{% addurlparameter output pdf %}">Export as pdf</a>
from django.template import Library, Node, resolve_variable, TemplateSyntaxError
register = Library()
class AddParameter(Node):
def __init__(self, varname, value):
self.varname = varname
self.value = value
def render(self, context):
req = resolve_variable('request',context)
params = req.GET.copy()
params[self.varname] = self.value
return '%s?%s' % (req.path, params.urlencode())
def addurlparameter(parser, token):
from re import split
bits = split(r'\s+', token.contents, 2)
if len(bits) < 2:
raise TemplateSyntaxError, "'%s' tag requires two arguments" % bits[0]
return AddParameter(bits[1],bits[2])
register.tag('addurlparameter', addurlparameter)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
If you want to be able to pass variables from template into the template tag you may use the following version:
Sample usage:
#
Please login first before commenting.