Templates

A template is a file on disk which can be used to render dynamic data provided by a view. repoze.bfg offers a number of ways to perform templating tasks out of the box, and provides add-on templating support through a set of bindings packages.

Out of the box, repoze.bfg provides templating via the Chameleon templating library. Chameleon provides support for two different types of templates: ZPT templates and text templates.

Before discussing how built-in templates are used in detail, we’ll discuss two ways to render templates within repoze.bfg in general: directly, and via renderer configuration.

Templates Used Directly

The most straightforward way to use a template within repoze.bfg is to cause it to be rendered directly within a view callable. You may use whatever API is supplied by a given templating engine to do so.

repoze.bfg provides various APIs that allow you to render templates directly from within a view callable. For example, if there is a Chameleon ZPT template named foo.pt in a directory in your application named templates, you can render the template from within the body of a view callable like so:

1
2
3
4
5
6
from repoze.bfg.renderers import render_to_response

def sample_view(request):
    return render_to_response('templates/foo.pt',
                              {'foo':1, 'bar':2},
                              request=request)

Warning

Earlier iterations of this documentation (pre-version-1.3) encouraged the application developer to use ZPT-specific APIs such as repoze.bfg.chameleon_zpt.render_template_to_response(), repoze.bfg.chameleon_zpt.render_template_to_iterable(), and repoze.bfg.chameleon_zpt.render_template() to render templates directly. This style of rendering still works, but at least for purposes of this documentation, those functions are deprecated. Application developers are encouraged instead to use the functions available in the repoze.bfg.renderers module to perform rendering tasks. This set of functions works to render templates for all renderer extensions registered with repoze.bfg.

The sample_view view callable above returns a response object which contains the body of the templates/foo.pt template. In this case, the templates directory should live in the same directory as the module containing the sample_view function. The template author will have the names foo and bar available as top-level names for replacement or comparison purposes.

In the example above, the path templates/foo.pt is relative to the directory in which the file which defines the view configuration lives. In this case, this is the directory containing the file that defines the sample_view function. Although a renderer path is usually just a simple relative pathname, a path named as a renderer can be absolute, starting with a slash on UNIX or a drive letter prefix on Windows.

The path can alternately be a resource specification in the form some.dotted.package_name:relative/path, making it possible to address template resources which live in another package. For example:

1
2
3
4
5
6
from repoze.bfg.renderers import render_to_response

def sample_view(request):
    return render_to_response('mypackage:templates/foo.pt',
                              {'foo':1, 'bar':2},
                              request=request)

A resource specification points at a file within a Python package. In this case, it points at a file named foo.pt within the templates directory of the mypackage package. Using a resource specification instead of a relative template name is usually a good idea, because calls to render_to_response using resource specifications will continue to work properly if you move the code containing them around.

In the examples above we pass in a keyword argument named request representing the current repoze.bfg request. Passing a request keyword argument will cause the render_to_response function to supply the renderer with more correct system values (see System Values Used During Rendering), because most of the information required to compose proper system values is present in the request. If you care about the correct system values being provided to the renderer being called (in particular, if your template relies on the name request or context, or if you’ve configured special renderer globals make sure to pass request as a keyword argument in every call to to a repoze.bfg.renderers.render_* function.

Every view must return a response object (except for views which use a renderer named via view configuration, which we’ll see shortly). The repoze.bfg.renders.render_to_response() function is a shortcut function that actually returns a response object.

Obviously not all APIs you might call to get respnonse data will return a response object. If you call a “response-ignorant” API that returns information you’d like to use as a response (such as when you render a template to a string), you must construct your own response object as necessary with the string as the body. For example, the repoze.bfg.renderers.render() API returns a string. We can manufacture a response object directly, and use that string as the body of the response:

1
2
3
4
5
6
7
8
9
from repoze.bfg.renderers import render
from webob import Response

def sample_view(request):
    result = render('mypackage:templates/foo.pt',
                    {'foo':1, 'bar':2},
                    request=request)
    response = Response(result)
    return response

Because view callable functions are typically the only code in repoze.bfg that need to know anything about templates, and because view functions are very simple Python, you can use whatever templating system you’re most comfortable with within repoze.bfg. Install the templating system, import its API functions into your views module, use those APIs to generate a string, then return that string as the body of a WebOb Response object.

For example, here’s an example of using raw Mako from within a repoze.bfg view:

1
2
3
4
5
6
7
8
from mako.template import Template
from webob import Response

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

You probably wouldn’t use this particular snippet in a project, because it’s easier to use the Mako renderer bindings which already exist for repoze.bfg named repoze.bfg.mako (available from PyPI). But if your favorite templating system is not supported as a renderer extension for BFG, you can create your own simple conmbination as shown above.

Note

If you use third-party templating languages without cooperating BFG bindings directly within view callables, the auto-template-reload strategy explained in Automatically Reloading Templates will not be available, nor will the template resource overriding capability explained in Overriding Resources be available, nor will it be possible to use any template using that language as a renderer. However, it’s reasonably easy to write custom templating system binding packages for use under repoze.bfg so that templates written in the language can be used as renderers. See Adding and Overriding Renderers for instructions on how to create your own template renderer and Available Add-On Template System Bindings for example packages.

If you need more control over the status code and content-type, or other response attributes from views that use direct templating, you may set attributes on the response that influence these values.

Here’s an example of changing the content-type and status of the response object returned by repoze.bfg.renderers.render_to_response():

from repoze.bfg.renderers.render_to_response

def sample_view(request):
    response = render_to_response('templates/foo.pt',
                                  {'foo':1, 'bar':2},
                                  request=request)
    response.content_type = 'text/plain'
    response.status_int = 204
    return response

Here’s an example of manufacturing a response object using the result of repoze.bfg.renderers.render() (a string):

1
2
3
4
5
6
7
8
9
from repoze.bfg.renderers import render
from webob import Response
def sample_view(request):
    result = render('mypackage:templates/foo.pt',
                    {'foo':1, 'bar':2},
                    request=request)
    response = Response(result)
    response.content_type = 'text/plain'
    return response

System Values Used During Rendering

When a template is rendered using repoze.bfg.renderers.render_to_response() or repoze.bfg.renderers.render(), the renderer representing the template will be provided with a number of system values. These values are provided in a dictionary to the renderer and include:

context
The current repoze.bfg context if request was provided as a keyword argument or None.
request
The request provided as a keyword argument.
renderer_name
The renderer name used to perform the rendering, e.g. mypackage:templates/foo.pt.

You can define more values which will be passed to every template executed as a result of rendering by defining renderer globals.

What any particular renderer does with them is up to the renderer itself, but most renderers, including al Chameleon renderers, make these names available as top-level template variables.

Templates Used as Renderers via Configuration

Instead of using the repoze.bfg.renderers.render_to_response() API within the body of a view function directly to render a specific template to a response, you may associate a template written in a supported templating language with a view indirectly by specifying it as a renderer in view configuration.

To use a renderer via view configuration, specify a template resource specification as the renderer argument or attribute to the view configuration of a view callable. Then return a dictionary from that view callable. The dictionary items returned by the view callable will be made available to the renderer template as top-level names.

The association of a template as a renderer for a view configuration makes it possible to replace code within a view callable that handles the rendering of a template.

Here’s an example of using a repoze.bfg.view.bfg_view decorator to specify a view configuration that names a template renderer:

1
2
3
4
5
from repoze.bfg.view import bfg_view

@bfg_view(renderer='templates/foo.pt')
def my_view(request):
    return {'foo':1, 'bar':2}

Note

It is not necessary to supply the request value as a key in the dictionary result returned from a renderer-configured view callable in order to ensure that the “most correct” system values are supplied to the renderer as it is when you use repoze.bfg.renderers.render() or repoze.bfg.renderers.render_to_response(). This is handled automatically.

Similar renderer configuration can be done imperatively and via ZCML. See Writing View Callables Which Use a Renderer. See also Built-In Renderers.

The renderer argument to the @bfg_view configuration decorator shown above is the template path. In the example above, the path templates/foo.pt is relative. Relative to what, you ask? Relative to the directory in which the file which defines the view configuration lives. In this case, this is the directory containing the file that defines the my_view function.

Although a renderer path is usually just a simple relative pathname, a path named as a renderer can be absolute, starting with a slash on UNIX or a drive letter prefix on Windows. The path can alternately be a resource specification in the form some.dotted.package_name:relative/path, making it possible to address template resources which live in another package.

Not just any template from any arbitrary templating system may be used as a renderer. Bindings must exist specifically for repoze.bfg to use a templating language template as a renderer. Currently, repoze.bfg has built-in support for two Chameleon templating languages: ZPT and text. See Built-In Renderers for a discussion of their details. repoze.bfg also supports the use of Jinja2 templates as renderers. See Available Add-On Template System Bindings.

By default, views rendered via a template renderer return a Response object which has a status code of 200 OK and a content-type of text/html. To vary attributes of the response of a view that uses a renderer, such as the content-type, headers, or status attributes, you must set attributes on the request object within the view before returning the dictionary. See Varying Attributes of Rendered Responses for more information.

The same set of system values are provided to templates rendered via a rendere view configuration as those provided to templates rendered imperatively. See System Values Used During Rendering.

Chameleon ZPT Templates

Like Zope, repoze.bfg uses ZPT (Zope Page Templates) as its default templating language. However, repoze.bfg uses a different implementation of the ZPT specification than Zope does: the Chameleon templating engine. The Chameleon engine complies largely with the Zope Page Template template specification. However, it is significantly faster.

The language definition documentation for Chameleon ZPT-style templates is available from the Chameleon website.

Warning

Chameleon only works on CPython platforms and Google App Engine. On Jython and other non-CPython platforms, you should use repoze.bfg.jinja2 instead. See Available Add-On Template System Bindings.

Given that there is a Chameleon ZPT template named foo.pt in a directory in your application named templates, you can render the template as a renderer like so:

1
2
3
4
5
from repoze.bfg.view import bfg_view

@bfg_view(renderer='templates/foo.pt')
def my_view(request):
    return {'foo':1, 'bar':2}

See also Built-In Renderers for more general information about renderers, including Chameleon ZPT renderers.

A Sample ZPT Template

Here’s what a simple Chameleon ZPT template used under repoze.bfg might look like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
 <!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://static.repoze.org/bfgdocs">repoze.bfg</a> web
       application framework.</h1>
   </body>
 </html>

Note the use of Genshi -style ${replacements} above. This is one of the ways that Chameleon ZPT differs from standard ZPT. The above template expects to find a project key in the set of keywords passed in to it via repoze.bfg.renderers.render() or repoze.bfg.renderers.render_to_response(). Typical ZPT attribute-based syntax (e.g. tal:content and tal:replace) also works in these templates.

Using ZPT Macros in repoze.bfg

When a renderer is used to render a template, repoze.bfg makes at least two top-level names available to the template by default: context and request. One of the common needs in ZPT-based templates is to use one template’s “macros” from within a different template. In Zope, this is typically handled by retrieving the template from the context. But having a hold of the context in repoze.bfg is not helpful: templates cannot usually be retrieved from models. To use macros in repoze.bfg, you need to make the macro template itself available to the rendered template by passing the template in which the macro is defined (or even the macro itself) into the rendered template. To make a macro available to the rendered template, you can retrieve a different template using the repoze.bfg.renderers.get_renderer() API, and pass it in to the template being rendered. For example, using a view configuration via a repoze.bfg.view.bfg_view decorator that uses a renderer:

1
2
3
4
5
6
7
from repoze.bfg.renderers import get_renderer
from repoze.bfg.view import bfg_view

@bfg_view(renderer='templates/mytemplate.pt')
def my_view(request):
    main = get_renderer('templates/master.pt').implementation()
    return {'main':main}

Where templates/master.pt might look like so:

1
2
3
4
5
6
7
8
9
 <html xmlns="http://www.w3.org/1999/xhtml"
       xmlns:tal="http://xml.zope.org/namespaces/tal"
       xmlns:metal="http://xml.zope.org/namespaces/metal">
   <span metal:define-macro="hello">
     <h1>
       Hello <span metal:define-slot="name">Fred</span>!
     </h1>
   </span>
 </html>

And templates/mytemplate.pt might look like so:

1
2
3
4
5
6
7
 <html xmlns="http://www.w3.org/1999/xhtml"
       xmlns:tal="http://xml.zope.org/namespaces/tal"
       xmlns:metal="http://xml.zope.org/namespaces/metal">
   <span metal:use-macro="main.macros['hello']">
     <span metal:fill-slot="name">Chris</span>
   </span>
 </html>

Templating with Chameleon Text Templates

repoze.bfg also allows for the use of templates which are composed entirely of non-XML text via Chameleon. To do so, you can create templates that are entirely composed of text except for ${name} -style substitution points.

Here’s an example usage of a Chameleon text template. Create a file on disk named mytemplate.txt in your project’s templates directory with the following contents:

Hello, ${name}!

Then in your project’s views.py module, you can create a view which renders this template:

1
2
3
4
5
from repoze.bfg.view import bfg_view

@bfg_view(renderer='templates/mytemplate.txt')
def my_view(request):
    return {'name':'world'}

When the template is rendered, it will show:

Hello, world!

If you’d rather use templates directly within a view callable (without the indirection of using a renderer), see repoze.bfg.chameleon_text for the API description.

See also Built-In Renderers for more general information about renderers, including Chameleon text renderers.

Side Effects of Rendering a Chameleon Template

When a Chameleon template is rendered from a file, the templating engine writes a file in the same directory as the template file itself as a kind of cache, in order to do less work the next time the template needs to be read from disk. If you see “strange” .py files showing up in your templates directory (or otherwise directly “next” to your templates), it is due to this feature.

If you’re using a version control system such as Subversion, you should cause it to ignore these files. Here’s the contents of the author’s svn propedit svn:ignore . in each of my templates directories.

1
2
*.pt.py
*.txt.py

Note that I always name my Chameleon ZPT template files with a .pt extension and my Chameleon text template files with a .txt extension so that these svn:ignore patterns work.

Automatically Reloading Templates

It’s often convenient to see changes you make to a template file appear immediately without needing to restart the application process. repoze.bfg allows you to configure your application development environment so that a change to a template will be automatically detected, and the template will be reloaded on the next rendering.

Warning

auto-template-reload behavior is not recommended for production sites as it slows rendering slightly; it’s usually only desirable during development.

In order to turn on automatic reloading of templates, you can use an environment variable setting or a configuration file setting.

To use an environment variable, start your application under a shell using the BFG_RELOAD_TEMPLATES operating system environment variable set to 1, For example:

$ BFG_RELOAD_TEMPLATES=1 bin/paster serve myproject.ini

To use a setting in the application .ini file for the same purpose, set the reload_templates key to true within the application’s configuration section, e.g.:

[app:main]
use = egg:MyProject#app
reload_templates = true

Nicer Exceptions in Templates

The exceptions raised by Chameleon templates when a rendering fails are sometimes less than helpful. repoze.bfg allows you to configure your application development environment so that exceptions generated by Chameleon during template compilation and execution will contain nicer debugging information.

Warning

template-debugging behavior is not recommended for production sites as it slows renderings; it’s usually only desirable during development.

In order to turn on template exception debugging, you can use an environment variable setting or a configuration file setting.

To use an environment variable, start your application under a shell using the BFG_DEBUG_TEMPLATES operating system environment variable set to 1, For example:

$ BFG_DEBUG_TEMPLATES=1 bin/paster serve myproject.ini

To use a setting in the application .ini file for the same purpose, set the debug_templates key to true within the application’s configuration section, e.g.:

[app:main]
use = egg:MyProject#app
debug_templates = true

With template debugging off, a NameError exception resulting from rendering a template with an undefined variable (e.g. ${wrong}) might end like this:

File "...", in __getitem__
  raise NameError(key)
NameError: wrong

Note that the exception has no information about which template was being rendered when the error occured. But with template debugging on, an exception resulting from the same problem might end like so:

RuntimeError: Caught exception rendering template.
 - Expression: ``wrong``
 - Filename:   /home/fred/env/bfgzodb/bfgzodb/templates/mytemplate.pt
 - Arguments:  renderer_name: bfgzodb:templates/mytemplate.pt
               template: <PageTemplateFile - at 0x1d2ecf0>
               xincludes: <XIncludes - at 0x1d3a130>
               request: <Request - at 0x1d2ecd0>
               project: bfgzodb
               macros: <Macros - at 0x1d3aed0>
               context: <MyModel None at 0x1d39130>
               view: <function my_view at 0x1d23570>

NameError: wrong

The latter tells you which template the error occurred in, as well as displaying the arguments passed to the template itself.

Note

Turning on debug_templates has the same effect as using the Chameleon environment variable CHAMELEON_DEBUG. See Chameleon Environment Variables for more information.

Chameleon Template Internationalization

See Chameleon Template Support for Translation Strings for information about supporting internationalized units of text within Chameleon templates.

Available Add-On Template System Bindings

Jinja2 template bindings are available for repoze.bfg in the repoze.bfg.jinja2 package. It lives in the Repoze Subversion repository at http://svn.repoze.org/repoze.bfg.jinja2; it is also available from PyPI.