Home > Articles > Open Source > Python

An Introduction to Python Web Development Using the Pyramid Framework, Part 6

  • Print
  • + Share This
  • 💬 Discuss
In Part 6 of his seven-part series on learning Python Pyramid, Jesse Smith covers how to use Pyramid templates.

If you haven't read Part 5 of this series, I recommend you do that before continuing with this article. In Part 5, we examined views and view configurations.

This article will cover templates. Templates are very important, as they're a big part of Python Pyramid, and using them will make your life easier and improve your application's overall design.

Templates render data provided by a view. Two main template libraries come with Pyramid: Chameleon and Mako. This article only covers Chameleon.

To get started, we'll first start with the basics on how to use templates directly, followed by how to render templates by using a renderer configuration.

Renderers were covered in some detail in Part 5 of this series.


Catch Up on All of the Articles in this Python Series

Jesse Smith has written six articles in this series. Here are the earlier installments:

Part 1
Part 4
Part 2
Part 5
Part 3
 


Using Templates Directly

As you might recall from Part 5, a view callable takes a request and returns a Response object, either directly or indirectly, by using a renderer.

With a view callable, we can display a template directly. Using the render_to_response function, we only need to pass the template file path as a parameter as the first argument to the function, and any top-level names as the second argument. You can also pass other values to the template as a set of key/value pairs. The example below passes in the template path and top-level names only:

from pyramid.renderers import render_to_response

def sample_view(request):
    return render_to_response('templates/myTemplate.pt',
                              {'myTemplate1':1, 'myTemplate2':2},
                              request=request)

You might be wondering where the Response object comes from, as all view configurations ultimately return a Response object. In this case, it's provided by the render_to_response function:

from pyramid.renderers import render_to_response
       def sample_view(request):
       return render_to_response('templates/myTemplate.pt',
                              {'myTemplate':1, 'mainTemplate':2},
                              request=request)

Another, more obvious way to manufacture a response when providing a template is to use the pyramid.renderers.render() API:

from mako.template import Template
from pyramid.response import Response

def make_view(request):
    template = Template(filename='/templates/template.pt')
    result = template.render(name=request.params['name'])
    response = Response(result)
    return response

In the example above, the Response object is passed the result from the method as a string.

To define the content type and response code, you can use the Response object, much as in other languages, including Java and .NET:

from pyramid.renderers import render
from pyramid.response import Response

def sample_view(request):
    result = render('mypackage:templates/myTemplate.pt',
                    {'myTemplate':1, 'mainTemplate':2},
                    request=request)
    response = Response(result)
    response.content_type = 'text/plain'
    return response

The render parameter takes the template path as the value. The top-level names are returned as a dictionary set of values. (This is covered in my article "An Introduction to Object-Oriented Concepts in Python, Part 3.")

Chameleon Templates

So far, you've learned how to render templates in a few different ways, but what makes this possible is a template engine, which is an API for working with templates. One template engine that comes with Pyramid is the Chameleon engine. Chameleon supports two types of templates called ZPT and text templates.

ZPT is a page template. Following is an example ZPT page template:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml"
       xmlns:tal="http://xml.zope.org/namespaces/tal">
 <head>
     <meta http-equiv="content-type" content="text/html; charset=utf-8" />
     <title>${project} Application</title>
 </head>
   <body>
      <h1 class="title">Welcome to <code>${project}</code>, an
       application generated by the <a
       href="http://docs.pylonsproject.org/projects/pyramid/current/"
      >pyramid</a> web
       application framework.</h1>
   </body>
 </html>

The template code above is part of the page you see when first bringing up the Python MyProject application on your web server. As you can see, the page takes parameters in the form of a format specifier.

Using parameters like this is common to Java Tag libraries and C# "format specifiers." The second set of parameters, a list of keywords and top-level searchable template names, provides the ${project} key with the key value from the Dictionary object, returned as a Response string.

The second type of Chameleon template is the simple text template. As you may have guessed, this is a more simplified version of a template, which only uses the values, without any markup code:

Hello, ${name}!

Now, to render the page, it's the same concept as with a ZPT template page. The key/value pair is still passed to the template with a view configuration, but directly through the Response object as a key/value pair:

from pyramid.view import view_config

@view_config(renderer='templates/myTemplate.txt')
def my_view(request):
    return {'name':'John'}

Conclusion

In this article, you learned about view templates and how they're used with view callables and returned as a Response. A manufactured response from rendering the template can be invoked in a view in different ways. You can use the render_to_response function, or a set of dictionary values using a view callable annotation, or a plain text template.

There are other templating engines, but this article covered only the Chameleon template engine. This engine has two types of templates: A ZPT template is used to render markup with a dictionary set of key/value parameters provided by a manufactured response, and a text page template uses a response string with no markup.

Templates are a big part of the Pyramid framework, and they can make your overall application design much easier to use. Part 7 of this series will cover the request and Response objects in greater detail, along with discussing how to use sessions and events.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus