| 300 | class URLNode(Node): |
| 301 | def __init__(self, view_name, args): |
| 302 | self.view_name = view_name |
| 303 | self.args = args |
| 304 | |
| 305 | def render(self, context): |
| 306 | from django.core.urlresolvers import reverse, NoReverseMatch |
| 307 | args = [arg.resolve(context) for arg in self.args] |
| 308 | project_name = settings.SETTINGS_MODULE.split('.')[0] |
| 309 | try: |
| 310 | return reverse(project_name + '.' + self.view_name, args=args) |
| 311 | except NoReverseMatch: |
| 312 | return '' |
| 313 | |
| 854 | def url(parser, token): |
| 855 | """ |
| 856 | Returns an absolute URL matching given view with its parameters. This is a mean to |
| 857 | define links that aren't tied to a particular url configuration. |
| 858 | |
| 859 | The first argument is a path to a view in the form ``app_name.view_name`` (without |
| 860 | the project name). Other arguments are values that will be filled in place of arguments |
| 861 | in the URL and thus should be all present. Currently only positional arguments are |
| 862 | supported. |
| 863 | |
| 864 | For example if you have a view ``app_name.client`` taking client's id and the |
| 865 | corresponding line in the urlconf looks like this: |
| 866 | |
| 867 | ('^client/(\d+)/$', 'app_name.client') |
| 868 | |
| 869 | ... and this app's urlconf is included into the project's urlconf under some path: |
| 870 | |
| 871 | ('^clients/', include('project_name.app_name.urls')) |
| 872 | |
| 873 | ... then in a template you can create a link for a certain client like this: |
| 874 | |
| 875 | {% url app_name.client client.id %} |
| 876 | |
| 877 | The URL will look like ``/clients/client/123/``. |
| 878 | """ |
| 879 | bits = token.contents.split() |
| 880 | if len(bits) < 2: |
| 881 | raise TemplateSyntaxError, "'url' takes at least one argument (path to a view)" |
| 882 | if len(bits) > 2: |
| 883 | args = [parser.compile_filter(arg) for arg in bits[2].split(',')] |
| 884 | else: |
| 885 | args = [] |
| 886 | return URLNode(bits[1], args) |
| 887 | url = register.tag(url) |
| 888 | |