Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Dynamic URL alias in templates

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})
like image 594
knipknap Avatar asked Dec 21 '25 04:12

knipknap


2 Answers

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:])
like image 122
Olivier Verdier Avatar answered Dec 24 '25 09:12

Olivier Verdier


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:])
like image 33
knipknap Avatar answered Dec 24 '25 10:12

knipknap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!