ВУЗ: Не указан
Категория: Не указан
Дисциплина: Не указана
Добавлен: 02.01.2026
Просмотров: 2735
Скачиваний: 0
11.2. SYSTEM VALUES USED DURING RENDERING
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 from pyramid.renderers import render_to_response
2
3 def sample_view(request):
4response = render_to_response(’templates/foo.pt’,
5 |
|
{’foo’:1, ’bar’:2}, |
6 |
|
request=request) |
7 |
response.content_type |
= ’text/plain’ |
8 |
response.status_int = |
204 |
9return response
Here’s an example of manufacturing a response object using the result of render() (a string):
1 |
from pyramid.renderers import render |
2 |
from pyramid.response import Response |
3 |
|
4 |
def sample_view(request): |
5result = render(’mypackage:templates/foo.pt’,
6 |
{’foo’:1, ’bar’:2}, |
7 |
request=request) |
8response = Response(result)
9 response.content_type = ’text/plain’
10 return response
11.2 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, or None.
request The request provided as a keyword argument.
125
11. TEMPLATES
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 and type.
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.
11.3 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}
126
11.3. TEMPLATES USED AS RENDERERS VIA CONFIGURATION
latex-note.png
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.
latex-warning.png
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.
127
11. TEMPLATES
Why Use A Renderer via View Configuration
Using a renderer in view configuration is usually a better way to render templates than using any rendering API directly from within a view callable because it makes the view callable more unit-testable. Views which use templating or rendering 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 parse information out of the response body (often HTML). View callables configured with renderers externally via view configuration typically return a dictionary, as above. Making assertions about results returned in a dictionary is almost always more direct and straightforward than needing to parse HTML.
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.
11.4 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.
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.
128
11.4. CHAMELEON ZPT TEMPLATES
11.4.1 A Sample ZPT Template
Here’s what a simple Chameleon ZPT template used under Pyramid might look like:
1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3<html xmlns="http://www.w3.org/1999/xhtml"
4xmlns:tal="http://xml.zope.org/namespaces/tal">
5<head>
6 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
7<title>${project} Application</title>
8</head>
9<body>
10<h1 class="title">Welcome to <code>${project}</code>, an
11application generated by the <a
12href="http://docs.pylonsproject.org/projects/pyramid/current/"
13>pyramid</a> web
14application framework.</h1>
15</body>
16</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.
11.4.2 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
from pyramid.renderers import get_renderer from pyramid.view import view_config
@view_config(renderer=’templates/mytemplate.pt’)
129