Generate URLs with the url() function in views

Author:Peter Bengtsson, Jan-Jaap Driessen

The ‘url()’ function makes it really easy to generate a URL for an object or by name or a combination of an object and a name. We’ll also show how to append a query string to the URL by passing a dictionary to the ‘url()’ function.

Purpose

You want to easily construct URLs in your view classes and view templates.

Prerequisities

A running Grok site with one or more views.

Step by step

The url() function is really easy to use and you should be able to throw it an object, a name or neither and it will construct the URL for you. If you omit the object parameter it will default to “self” where “self” is either the object you’re doing this in or the view you’re calling it form. As an added bonus you can use url() to construct a URL with a CGI query string that is URL encoded.

Suppose you have a view class called “FooView” and an accompanying template file called fooview.pt. If you want to add a URL to the template itself you can do that with this TAL code.

The following combinations of object, name and data are allowed:

<a tal:attributes="href view/url">Link to this page</a>

This is the same as using the python: syntax:

<a tal:attributes="href python: view.url()">Link to this page</a>

When not specifying the object, url() defaults to the view itself:

<a tal:attributes="href python: view.url(view)">Link to this page</a>

To make a url to the container of the view, use context:

<a tal:attributes="href python: view.url(context)">Link to the container</a>

To make a url to a different view on the current container, use context and name:

<a tal:attributes="href python: view.url(context, 'add')">
  Link to adding to the container
</a>

Using the data argument, a query string is appended to the generated URL:

<a tal:attributes="href python: view.url(context, 'add', data={'a':1, 'b':2})">
  Link to adding to the container, with a=1&amp;b=2
</a>

You can supply unicode and lists in the data argument. These are properly escaped.

<a tal:attributes="href python: view.url(data={'name':u'Pjötr'})">
  ?name=Pj%C3%B6tr
</a>
<a tal:attributes="href python: view.url(data={'id':[1,2,3]})">
  ?id=1&amp;id=2&amp;id=3
</a>
<a tal:attributes="href python: view.url(data={'name':[u'Pjötr', 'Sonja']})">
  ?name=Pj%C3%B6tr&amp;name=Sonja
</a>

Further information

You can still use Zope’s automatic type casting of parameters:

<a tal:attributes="href python: view.url(data={'amount:int': 25})">
  ?amount%3Aint=25
</a>