Templates¶
A template is a file on disk which can be used to render dynamic data provided by a view. Pyramid 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, Pyramid provides templating via the Chameleon and Mako templating libraries. 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 Pyramid in general: directly, and via renderer configuration.
Using Templates Directly¶
The most straightforward way to use a template within Pyramid 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.
Pyramid 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 named
templates
in your application, you can render the template from
within the body of a view callable like so:
1 2 3 4 5 6 | from pyramid.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
pyramid.chameleon_zpt.render_template_to_response()
and
pyramid.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 pyramid.renderers
module to perform
rendering tasks. This set of functions works to render templates
for all renderer extensions registered with Pyramid.
The sample_view
view callable function 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 containing the file which defines the view configuration.
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.
Warning
Only Chameleon templates support defining a renderer for a
template relative to the location of the module where the view
callable is defined. Mako templates, and other templating system
bindings work differently. In particular, Mako templates use a
“lookup path” as defined by the mako.directories
configuration
file instead of treating relative paths as relative to the current
view module. See Templating With Mako Templates.
The path can alternately be a asset specification in the form
some.dotted.package_name:relative/path
. This makes it possible to
address template assets which live in another package. For example:
1 2 3 4 5 6 | from pyramid.renderers import render_to_response
def sample_view(request):
return render_to_response('mypackage:templates/foo.pt',
{'foo':1, 'bar':2},
request=request)
|
An asset 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
asset specification instead of a relative template name is usually
a good idea, because calls to render_to_response
using asset
specifications will continue to work properly if you move the code
containing them around.
Note
Mako templating system bindings also respect absolute asset
specifications as an argument to any of the render*
commands. If a
template name defines a :
(colon) character and is not an absolute
path, it is treated as an absolute asset specification.
In the examples above we pass in a keyword argument named request
representing the current Pyramid 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 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
pyramid.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 pyramid.renderers.render_to_response()
function is a shortcut function that actually returns a response
object. This allows the example view above to simply return the result
of its call to render_to_response()
directly.
Obviously not all APIs you might call to get response data will return a
response object. For example, you might render one or more templates to
a string that you want to use as response data. The
pyramid.renderers.render()
API renders a template to 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 pyramid.renderers import render
from pyramid.response 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 Pyramid 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 Pyramid. 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 Pyramid Response object.
For example, here’s an example of using “raw” Mako from within a Pyramid view:
1 2 3 4 5 6 7 8 | from mako.template import Template
from pyramid.response 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 in Pyramid. But if your favorite templating system is not supported as a renderer extension for Pyramid, you can create your own simple combination as shown above.
Note
If you use third-party templating languages without cooperating Pyramid bindings directly within view callables, the auto-template-reload strategy explained in Automatically Reloading Templates will not be available, nor will the template asset overriding capability explained in Overriding Assets 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 Pyramid so that templates written in the language can be used as renderers. See Adding and Changing 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
render_to_response()
:
1 2 3 4 5 6 7 8 9 | from pyramid.renderers import 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 render()
(a string):
1 2 3 4 5 6 7 8 9 10 | from pyramid.renderers import render
from pyramid.response 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
render_to_response()
or
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 Pyramid context if
request
was provided as a keyword argument, orNone
. request
- The request provided as a keyword argument.
renderer_name
- The renderer name used to perform the rendering,
e.g.
mypackage:templates/foo.pt
. renderer_info
- An object implementing the
pyramid.interfaces.IRendererInfo
interface. Basically, an object with the following attributes:name
,package
andtype
.
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 these system values is up to the renderer itself, but most template renderers, including Chameleon and Mako renderers, make these names available as top-level template variables.
Templates Used as Renderers via Configuration¶
An alternative to using render_to_response()
to render templates manually in your view callable code, is
to specify the template as a renderer in your
view configuration. This can be done with any of the
templating languages supported by Pyramid.
To use a renderer via view configuration, specify a template
asset 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 view_config
decorator to specify a view configuration that names a
template renderer:
1 2 3 4 5 | from pyramid.view import view_config
@view_config(renderer='templates/foo.pt')
def my_view(request):
return {'foo':1, 'bar':2}
|
Note
You do not need to supply the request
value as a key
in the dictionary result returned from a renderer-configured view
callable. Pyramid automatically supplies this value for
you so that the “most correct” system values are provided to
the renderer.
Warning
The renderer
argument to the @view_config
configuration decorator
shown above is the template path. In the example above, the path
templates/foo.pt
is relative. Relative to what, you ask? Because
we’re using a Chameleon renderer, it means “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. View-configuration-relative asset specifications work only
in Chameleon, not in Mako templates.
Similar renderer configuration can be done imperatively. See Writing View Callables Which Use a Renderer. See also Built-In Renderers.
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 an asset
specification in the form some.dotted.package_name:relative/path
, making
it possible to address template assets 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 Pyramid to use a templating language template as a renderer. Currently, Pyramid has built-in support for two Chameleon templating languages: ZPT and text, and the Mako templating system. See Built-In Renderers for a discussion of their details. Pyramid 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
use the API of the pyramid.response.Response
object exposed as
request.response
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 renderer view configuration as those provided to templates rendered imperatively. See System Values Used During Rendering.
Chameleon ZPT Templates¶
Like Zope, Pyramid uses ZPT (Zope Page Templates) as its default templating language. However, Pyramid 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 Mako (see Templating With Mako Templates) or
pyramid_jinja2
instead. See
Available Add-On Template System Bindings.
Given 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 pyramid.view import view_config
@view_config(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 Pyramid might look like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <!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>
|
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 render()
or
render_to_response()
. Typical ZPT
attribute-based syntax (e.g. tal:content
and tal:replace
) also
works in these templates.
Using ZPT Macros in Pyramid¶
When a renderer is used to render a template, Pyramid 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 the
context in Pyramid is a resource object, and templates cannot
usually be retrieved from resources. To use macros in Pyramid, you
need to make the macro template itself available to the rendered template by
passing the macro template, or even the macro itself, into the rendered
template. To do this you can use the pyramid.renderers.get_renderer()
API to retrieve the macro template, and pass it into the template being
rendered via the dictionary returned by the view. For example, using a
view configuration via a view_config
decorator
that uses a renderer:
1 2 3 4 5 6 7 | from pyramid.renderers import get_renderer
from pyramid.view import view_config
@view_config(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¶
Pyramid 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 pyramid.view import view_config
@view_config(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 pyramid.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 configure 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.
Nicer Exceptions in Chameleon Templates¶
The exceptions raised by Chameleon templates when a rendering fails are sometimes less than helpful. Pyramid 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 PYRAMID_DEBUG_TEMPLATES
operating system environment
variable set to 1
, For example:
$ PYRAMID_DEBUG_TEMPLATES=1 bin/paster serve myproject.ini
To use a setting in the application .ini
file for the same
purpose, set the pyramid.debug_templates
key to true
within
the application’s configuration section, e.g.:
1 2 3 | [app:main]
use = egg:MyProject
pyramid.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/proj/proj/templates/mytemplate.pt
- Arguments: renderer_name: proj:templates/mytemplate.pt
template: <PageTemplateFile - at 0x1d2ecf0>
xincludes: <XIncludes - at 0x1d3a130>
request: <Request - at 0x1d2ecd0>
project: proj
macros: <Macros - at 0x1d3aed0>
context: <MyResource 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 pyramid.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.
Templating With Mako Templates¶
Mako is a templating system written by Mike Bayer. Pyramid has built-in bindings for the Mako templating system. The language definition documentation for Mako templates is available from the Mako website.
To use a Mako template, given a Mako template file named foo.mak
in the templates
subdirectory in your application package named
mypackage
, you can configure the template as a renderer like so:
1 2 3 4 5 | from pyramid.view import view_config
@view_config(renderer='foo.mak')
def my_view(request):
return {'project':'my project'}
|
For the above view callable to work, the following setting needs to be
present in the application stanza of your configuration’s ini
file:
mako.directories = mypackage:templates
This lets the Mako templating system know that it should look for templates
in the templates
subdirectory of the mypackage
Python package. See
Mako Template Render Settings for more information about the
mako.directories
setting and other Mako-related settings that can be
placed into the application’s ini
file.
A Sample Mako Template¶
Here’s what a simple Mako template used under Pyramid might look like:
1 2 3 4 5 6 7 8 9 10 11 | <html>
<head>
<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>
|
This template doesn’t use any advanced features of Mako, only the
${}
replacement syntax for names that are passed in as
renderer globals. See the the Mako documentation to use more advanced features.
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. Pyramid 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, or a configuration file setting.
To use an environment variable, start your application under a shell
using the PYRAMID_RELOAD_TEMPLATES
operating system environment
variable set to 1
, For example:
$ PYRAMID_RELOAD_TEMPLATES=1 bin/paster serve myproject.ini
To use a setting in the application .ini
file for the same
purpose, set the pyramid.reload_templates
key to true
within the
application’s configuration section, e.g.:
1 2 3 | [app:main]
use = egg:MyProject
pyramid.reload_templates = true
|
Available Add-On Template System Bindings¶
Jinja2 template bindings are available for Pyramid in the
pyramid_jinja2
package. You can get the latest release of
this package from the
Python package index
(pypi).