I am trying to use a template that contains a link such as this:
<a href="{% url search query,page.previous_page_number %}">previous</a>
I am trying to use it in multiple contexts; in other words, the URL alias "search" needs to point to a different target, depending on the view that renders the template.
Is there a way to pass such an alias to the template, such that the following (or similar) works?:
direct_to_template(request, 'my_template.html', {'search': my_url_alias})
As far as I know, you can't, because, for a reason I do not understand, the url tag does not take a string as input argument.
What you have to do is to roll out your own template tag, based on the implementation of the url templatetag in django, using a variable as a first argument.
I use something like this (name it as you wish):
class NavUrlNode(Node):
def __init__(self, *args):
self.name_var = Variable(args[0])
self.args=[]
for ii in range(1,args.__len__()):
self.args.append(Variable(args[ii]))
def render(self, context):
name = self.name_var.resolve(context)
args=[]
for ii in range(self.args.__len__()):
args.append(self.args[ii].resolve(context))
return reverse(name, args=args)
@register.tag
def navigation_url(parser, token):
args = token.split_contents()
return NavUrlNode(*args[1:])
Here's a slight improvement on Olivier's solution:
from django.template import Library, Node, Variable
from django.core.urlresolvers import reverse
register = Library()
class DynUrlNode(Node):
def __init__(self, *args):
self.name_var = Variable(args[0])
self.args = [Variable(a) for a in args[1].split(',')]
def render(self, context):
name = self.name_var.resolve(context)
args = [a.resolve(context) for a in self.args]
return reverse(name, args = args)
@register.tag
def dynurl(parser, token):
args = token.split_contents()
return DynUrlNode(*args[1:])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With