Login

Variable resolving URL template tag

Author:
UloPe
Posted:
March 9, 2009
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months 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.