TurboGears: 20 Minute Wiki, Page 5

## Converting incoming arguments

Something that's a little ugly in that save method is the 'if new == "True"'. Wouldn't it be nicer to just use the more pythonic 'if new'? Piece of cake... we just need to use a validator. First, we need an import:

    from turbogears import validators

Then, we specify the validator. The StringBoolean validator converts a string like "True" into the proper boolean. Doing that, we can change to using "if new". Here's the top of the save method:

<![CDATA[ @turbogears.expose(validators=dict(new=validators.StringBoolean())) def save(self, pagename, data, submit, new): hub.begin() if new: page = Page(pagename=pagename, data=data) ]]>

## Adding a page list

Most wikis have a feature that lets you view an index of the pages. We can add that to our wiki easily, so let's do it!

We'll start with a new template, pagelist.kid. To make things easy, we'll start with the page.kid template as a starter again:

    cd wiki20/templates
    cp page.kid pagelist.kid
    cd ../..

Change the body of the pagelist.kid template to look like this:

<![CDATA[ <body> <h1>All Of Your Pages</h1> <ul> <li py:for="pagename in pages"><a href="$${std.url('/' + pagename)}" py:content="pagename">Page Name Here.</a></li> </ul> </body> ]]>

Feel free to add "Are Belong To Us" to the heading, if you feel you must.

Just as with the other templates, you can open pagelist.kid directly in a browser. You can see that we'll get a bulleted list of links to the pages. This is our first use of py:for, and you can see it's straightforward. The li element will be repeated for each iteration of the for loop, and the for loop is specified just as it is in Python.

Let's add a link at the bottom of the master.kid template to get to the complete list of pages:

Since we're referring to a "pagelist" method, we should probably create it!

<![CDATA[ @turbogears.expose(html="wiki20.templates.pagelist") def pagelist(self): pages = [page.pagename for page in Page.select(orderBy=Page.q.pagename)] return dict(pages=pages) ]]>

This is our first use of Page.select. We're not doing anything fancy. We're just selecting all of the Page objects from the database, putting them in order by pagename. The "Page.q.pagename" represents the "pagename" attribute as a query parameter. Page.select returns a SelectResults object which you can iterate over, making the one liner above easy.

You can see your pagelist by clicking the link at the bottom of your pages or going directly to http://localhost:8080/pagelist.

Continue on to page 6