Login

Variable resolving URL template tag

Author:
UloPe
Posted:
March 9, 2009
Language:
Python
Version:
1.0
Tags:
template tag url context variable resolve resolving
Score:
2 (after 2 ratings)

DEPRECATED, use django-reversetag @ github instead.

If you want to be able to use context variables as argument for the "url" template tag this is for you.

Just put this code somwhere where it will be run early (like your app's _ init _.py) and of you go.

Usage: {% url name_of_view_or_variable arg1 arg2 %}

NOTE: This may possibly break your site! Every view name that is passed to url will be tried to be resolved as a context variable first! So if there is a variable coincidentally named like one of your views THEN IT WILL BREAK.

So far it works great for me, but keep an eye out for name clashes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.template import defaulttags, VariableDoesNotExist, Variable

class ResolvingURLNode(defaulttags.URLNode):
    def render(self, context):
        original_view_name = self.view_name
        try:
            self.view_name = Variable(self.view_name).resolve(context)
        except VariableDoesNotExist:
            pass
        ret = super(defaulttags.URLNode, self).render(context)
        # restore view_name in case this node is reused (e.g in a loop) in 
        # which case the variable might resolve to something else in the next iteration)
        self.view_name = original_view_name
        return ret

defaulttags.URLNode = ResolvingURLNode

More like this

  1. Support for {% macro %} tags in templates, version 2 by mludvig 7 years, 11 months ago
  2. Subdirectory and subcontext include template tag with examples by t_rybik 5 years, 4 months ago
  3. "Partial Templates" - an alternative to "include" by vigrid 6 years, 6 months ago
  4. Manipulate URL query strings using context variables using a template tag by JHsaunders 4 years, 9 months ago
  5. A templatetag to insert the output of another view (or local URL) by jamesgpearce 6 years, 1 month ago

Comments

t_rybik (on April 29, 2010):

It should be:

 super(ResolvingURLNode, self).render(context)

but besides that all cool.

#

Please login first before commenting.