views:

382

answers:

2

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})
+1  A: 

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:])
Olivier
Excellent! Thanks. Note that multiple arguments won't work in your solution, however. I'll add another answer that fixes these issues (and hopefully makes things a little simpler).
knipknap
+1  A: 

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:])
knipknap