Skip to content

Latest commit

 

History

History
531 lines (411 loc) · 19.5 KB

templates.rst

File metadata and controls

531 lines (411 loc) · 19.5 KB

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 templates are used in detail, we'll discuss two ways to render templates within repoze.bfg in general: directly, and via renderer configuration.

single: templates used directly single: Mako

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 Chameleon 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 view callable like so:

from repoze.bfg.chameleon_zpt import render_template_to_response

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

The sample_view view callable above returns a response object which contains the body of the template/foo.pt template. The template author will have the names foo and bar available as top-level names for replacement or comparison purposes.

Every views must return a response object (except for views which use a renderer, which we'll see shortly). The repoze.bfg.chameleon_zpt.render_template_to_response function is a shortcut function that actually returns a response object, but not all template APIs know about responses. When you use an template API that is "response-ignorant" you can also easily render a template to a string, and construct your own response object as necessary with the string as the body.

For example, the repoze.bfg.chameleon_zpt.render_template API returns a string. We can manufacture a response object directly, and use that string as the body of the response:

from repoze.bfg.chameleon_zpt import render_template
from webob import Response

def sample_view(request):
    result = render_template('templates/foo.pt', foo=1, bar=2)
    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 Mako from within a repoze.bfg view:

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

Note

If you use third-party templating languages without cooperating BFG bindings directly within view callables, the auto-template-reload strategy explained in reload_templates_section will not be available, nor will the template resource overriding capability explained in overriding_resources_section 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_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.chameleon_zpt.render_template_to_response:

from repoze.bfg.chameleon_zpt import render_template_to_response

def sample_view(request):
    response = render_template_to_response('templates/foo.pt', foo=1, bar=2)
    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.chameleon_zpt.render_template (a string):

from repoze.bfg.chameleon_zpt import render_template
from webob import Response
def sample_view(request):
    result = render_template('templates/foo.pt', foo=1, bar=2)
    response = Response(result)
    response.content_type = 'text/plain'
    return response

single: templates used as renderers single: template renderers single: renderer (template)

Templates Used as Renderers

Instead of using templating system APIs within a the body of a view function directly to render a specific template, you may associate a template written in a supported templating language with a view indirectly by specifying it as a renderer.

To use a renderer, 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:

from repoze.bfg.view import bfg_view

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

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.

When a template renderer is used to render the result of a view callable, several names are passed into the template as top-level names by default, including context and request. Similar renderer configuration can be done imperatively and via ZCML. See views_which_use_a_renderer. See also built_in_renderers.

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_template_system_bindings.

Why Use A Renderer

Using a renderer is usually a better way to render templates than using any templating API directly from within a view callable because it makes the view callable more unit-testable. Views which use templating APIs directly must return a Response object. Making testing assertions about response objects is typically an indirect process, because it means that your test code often needs to somehow needs to parse information out of the response body (often HTML). View callables which use renderers typically return a dictionary, and making assertions about the information is almost always more direct than needing to parse HTML. Specifying a renderer from within ZCML (as opposed to imperatively or via a bfg_view decorator, or using a template directly from within a view callable) also makes it possible for someone to modify the template used to render a view without needing to fork your code to do so. See extending_chapter for more information.

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 response_request_attrs for more information.

single: Chameleon ZPT templates single: ZPT templates (Chameleon)

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_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:

from repoze.bfg.view import bfg_view

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

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

See also built_in_renderers for more general information about renderers, including Chameleon ZPT renderers.

single: sample template

A Sample ZPT Template

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

<!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.chameleon_zpt.render_template or repoze.bfg.render_template_to_response. Typical ZPT attribute-based syntax (e.g. tal:content and tal:replace) also works in these templates.

single: ZPT macros single: Chameleon ZPT macros

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 template is to 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 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.chameleon_zpt.get_template 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:

from repoze.bfg.chameleon_zpt import get_template
from repoze.bfg.view import bfg_view

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

Where templates/master.pt might look like so:

<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:

<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>

single: Chameleon text templates

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:

from repoze.bfg.chameleon_zpt import get_template
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 chameleon_text_module for the API description.

See also built_in_renderers for more general information about renderers, including Chameleon text renderers.

single: template renderer side effects

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.

*.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.

single: automatic reloading of templates single: template automatic reload

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 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

single: template internationalization single: internationalization (of templates)

Chameleon Template Internationalization

See the internationalization chapter of the Chameleon documentation for information about supporting internationalized units of text within Chameleon templates.

single: template system bindings single: Jinja2 single: Genshi

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.