Vance Dubberly wrote:
> I'm not really the kind guy  to hardcode the prefix into all my 
> templates and so on.

There is not yet officially introduced and documented but working 
feature (The Right Feature!) for making URLs in your templates to 
automatically point to your views by their current path. It's called 
'reverse URL lookup'. It works by scanning actual regexps in your urlconf.

I've created a template tag that wraps it to be usable in templates:

     class URLNode(template.Node):
       def __init__(self, view_name, args):
         self.view_name = view_name
         self.args = args

       def render(self, context):
         from django.core.urlresolvers import reverse, NoReverseMatch
         args = [arg.resolve(context) for arg in self.args]
         project_name = settings.SETTINGS_MODULE.split('.')[0]
         try:
           return reverse(project_name + '.' + self.view_name, args=args)
         except NoReverseMatch:
           return ''

     @register.tag
     def url(parser, token):
       bits = token.contents.split()
       if len(bits) > 2:
         args = [parser.compile_filter(arg) for arg in bits[2].split(',')]
       else:
         args = []
       return URLNode(bits[1], args)

The usage is:

     {% url app_name.views.artist artist.id %}

I.e. you provide a path to a view and actual parameters that it accepts 
and it returns something like '/path/to/your/project/artist/15/' 
('artist' and '15' are for example).

It's a bit limited since it works only with positional arguments in 
views but not with keyword ones. This is not hard to do in code since 
'reverse' function itself already support it. I just couldn't come up 
with a nice syntax for a tag :-)

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---

Reply via email to