Steve Piercy
2017-06-26 260895df7aa9073d09090aabfdea7e52c262f8bc
commit | author | age
e45645 1 .. _templates_chapter:
CM 2
9cafa3 3 Templates
CM 4 =========
5
ac568b 6 A :term:`template` is a file on disk which can be used to render dynamic data
SP 7 provided by a :term:`view`.  :app:`Pyramid` offers a number of ways to perform
8 templating tasks out of the box, and provides add-on templating support through
9 a set of bindings packages.
9ec2d6 10
ac568b 11 Before discussing how built-in templates are used in detail, we'll discuss two
SP 12 ways to render templates within :app:`Pyramid` in general: directly and via
13 renderer configuration.
9cafa3 14
8c56ae 15 .. index::
9ec2d6 16    single: templates used directly
8c56ae 17
9ec2d6 18 .. _templates_used_directly:
a9fed7 19
470ad6 20 Using Templates Directly
CD 21 ------------------------
9cafa3 22
ac568b 23 The most straightforward way to use a template within :app:`Pyramid` is to
SP 24 cause it to be rendered directly within a :term:`view callable`.  You may use
25 whatever API is supplied by a given templating engine to do so.
9cafa3 26
ac568b 27 :app:`Pyramid` provides various APIs that allow you to render templates directly
SP 28 from within a view callable.  For example, if there is a :term:`Chameleon` ZPT
29 template named ``foo.pt`` in a directory named ``templates`` in your
30 application, you can render the template from within the body of a view
31 callable like so:
9cafa3 32
0bd110 33 .. code-block:: python
CM 34    :linenos:
6b9fd1 35
fec0f0 36    from pyramid.renderers import render_to_response
9ec2d6 37
6103bf 38    def sample_view(request):
368746 39        return render_to_response('templates/foo.pt',
SP 40                                  {'foo':1, 'bar':2},
250c02 41                                  request=request)
CM 42
c05651 43 The ``sample_view`` :term:`view callable` function above returns a
ac568b 44 :term:`response` object which contains the body of the ``templates/foo.pt``
SP 45 template.  In this case, the ``templates`` directory should live in the same
46 directory as the module containing the ``sample_view`` function.  The template
47 author will have the names ``foo`` and ``bar`` available as top-level names for
48 replacement or comparison purposes.
f6a2c7 49
250c02 50 In the example above, the path ``templates/foo.pt`` is relative to the
ac568b 51 directory containing the file which defines the view configuration. In this
SP 52 case, this is the directory containing the file that defines the
53 ``sample_view`` function.  Although a renderer path is usually just a simple
54 relative pathname, a path named as a renderer can be absolute, starting with a
55 slash on UNIX or a drive letter prefix on Windows. The path can alternatively
56 be an :term:`asset specification` in the form
57 ``some.dotted.package_name:relative/path``. This makes it possible to address
58 template assets which live in another package.  For example:
9ec2d6 59
CM 60 .. code-block:: python
61    :linenos:
62
fec0f0 63    from pyramid.renderers import render_to_response
250c02 64
CM 65    def sample_view(request):
3de42f 66        return render_to_response('mypackage:templates/foo.pt',
CM 67                                  {'foo':1, 'bar':2},
250c02 68                                  request=request)
CM 69
ac568b 70 An asset specification points at a file within a Python *package*. In this
SP 71 case, it points at a file named ``foo.pt`` within the ``templates`` directory
72 of the ``mypackage`` package.  Using an asset specification instead of a
73 relative template name is usually a good idea, because calls to
74 :func:`~pyramid.renderers.render_to_response` using asset specifications will
75 continue to work properly if you move the code containing them to another
76 location.
250c02 77
CM 78 In the examples above we pass in a keyword argument named ``request``
ac568b 79 representing the current :app:`Pyramid` request. Passing a request keyword
SP 80 argument will cause the ``render_to_response`` function to supply the renderer
81 with more correct system values (see :ref:`renderer_system_values`), because
82 most of the information required to compose proper system values is present in
83 the request.  If your template relies on the name ``request`` or ``context``,
84 or if you've configured special :term:`renderer globals`, make sure to pass
043ccd 85 ``request`` as a keyword argument in every call to a
818768 86 ``pyramid.renderers.render_*`` function.
250c02 87
ac568b 88 Every view must return a :term:`response` object, except for views which use a
SP 89 :term:`renderer` named via view configuration (which we'll see shortly).  The
90 :func:`pyramid.renderers.render_to_response` function is a shortcut function
91 that actually returns a response object. This allows the example view above to
92 simply return the result of its call to ``render_to_response()`` directly.
250c02 93
c53d82 94 Obviously not all APIs you might call to get response data will return a
ac568b 95 response object. For example, you might render one or more templates to a
SP 96 string that you want to use as response data.  The
97 :func:`pyramid.renderers.render` API renders a template to a string. We can
98 manufacture a :term:`response` object directly, and use that string as the body
99 of the response:
250c02 100
CM 101 .. code-block:: python
102    :linenos:
103
fec0f0 104    from pyramid.renderers import render
94b889 105    from pyramid.response import Response
9ec2d6 106
CM 107    def sample_view(request):
368746 108        result = render('mypackage:templates/foo.pt',
SP 109                        {'foo':1, 'bar':2},
250c02 110                        request=request)
9ec2d6 111        response = Response(result)
CM 112        return response
113
114 Because :term:`view callable` functions are typically the only code in
fd5ae9 115 :app:`Pyramid` that need to know anything about templates, and because view
ac568b 116 functions are very simple Python, you can use whatever templating system with
SP 117 which you're most comfortable within :app:`Pyramid`.  Install the templating
118 system, import its API functions into your views module, use those APIs to
119 generate a string, then return that string as the body of a :app:`Pyramid`
9ec2d6 120 :term:`Response` object.
CM 121
f1aaf1 122 For example, here's an example of using "raw" Mako_ from within a
MM 123 :app:`Pyramid` :term:`view`:
9ec2d6 124
CM 125 .. code-block:: python
126    :linenos:
127
128    from mako.template import Template
94b889 129    from pyramid.response import Response
9ec2d6 130
CM 131    def make_view(request):
132        template = Template(filename='/templates/template.mak')
133        result = template.render(name=request.params['name'])
134        response = Response(result)
135        return response
250c02 136
7698bd 137 You probably wouldn't use this particular snippet in a project, because it's
ac568b 138 easier to use the supported :ref:`Mako bindings
SP 139 <available_template_system_bindings>`. But if your favorite templating system
140 is not supported as a renderer extension for :app:`Pyramid`, you can create
141 your own simple combination as shown above.
9ec2d6 142
CM 143 .. note::
144
fec0f0 145    If you use third-party templating languages without cooperating
fd5ae9 146    :app:`Pyramid` bindings directly within view callables, the
ac568b 147    auto-template-reload strategy explained in :ref:`reload_templates_section`
SP 148    will not be available, nor will the template asset overriding capability
149    explained in :ref:`overriding_assets_section` be available, nor will it be
150    possible to use any template using that language as a :term:`renderer`.
151    However, it's reasonably easy to write custom templating system binding
152    packages for use under :app:`Pyramid` so that templates written in the
153    language can be used as renderers. See
154    :ref:`adding_and_overriding_renderers` for instructions on how to create
155    your own template renderer and :ref:`available_template_system_bindings`
156    for example packages.
9ec2d6 157
ac568b 158 If you need more control over the status code and content-type, or other
SP 159 response attributes from views that use direct templating, you may set
160 attributes on the response that influence these values.
9ec2d6 161
ac568b 162 Here's an example of changing the content-type and status of the response
SP 163 object returned by :func:`~pyramid.renderers.render_to_response`:
9ec2d6 164
CM 165 .. code-block:: python
166    :linenos:
167
9d33a1 168    from pyramid.renderers import render_to_response
9ec2d6 169
CM 170    def sample_view(request):
3de42f 171        response = render_to_response('templates/foo.pt',
CM 172                                      {'foo':1, 'bar':2},
250c02 173                                      request=request)
9ec2d6 174        response.content_type = 'text/plain'
CM 175        response.status_int = 204
176        return response
177
ac568b 178 Here's an example of manufacturing a response object using the result of
SP 179 :func:`~pyramid.renderers.render` (a string):
07a69e 180
0bd110 181 .. code-block:: python
CM 182    :linenos:
07a69e 183
fec0f0 184    from pyramid.renderers import render
94b889 185    from pyramid.response import Response
0b4277 186
6103bf 187    def sample_view(request):
3de42f 188        result = render('mypackage:templates/foo.pt',
368746 189                        {'foo':1, 'bar':2},
250c02 190                        request=request)
0bd110 191        response = Response(result)
CM 192        response.content_type = 'text/plain'
193        return response
6b9fd1 194
8c56ae 195 .. index::
CM 196    single: templates used as renderers
c5f24b 197    single: template renderers
CM 198    single: renderer (template)
8c56ae 199
250c02 200
6ce1e0 201 .. index::
CM 202    pair: renderer; system values
203
250c02 204 .. _renderer_system_values:
CM 205
206 System Values Used During Rendering
207 -----------------------------------
208
ac568b 209 When a template is rendered using :func:`~pyramid.renderers.render_to_response`
SP 210 or :func:`~pyramid.renderers.render`, or a ``renderer=`` argument to view
eb3394 211 configuration (see :ref:`templates_used_as_renderers`), the renderer
CM 212 representing the template will be provided with a number of *system* values.
213 These values are provided to the template:
250c02 214
CM 215 ``request``
eb3394 216   The value provided as the ``request`` keyword argument to
CM 217   ``render_to_response`` or ``render`` *or* the request object passed to the
218   view when the ``renderer=`` argument to view configuration is being used to
219   render the template.
220
221 ``req``
222   An alias for ``request``.
223
224 ``context``
225   The current :app:`Pyramid` :term:`context` if ``request`` was provided as a
ac568b 226   keyword argument to ``render_to_response`` or ``render``, or ``None`` if the
SP 227   ``request`` keyword argument was not provided.  This value will always be
228   provided if the template is rendered as the result of a ``renderer=``
229   argument to the view configuration being used.
250c02 230
CM 231 ``renderer_name``
ac568b 232   The renderer name used to perform the rendering, e.g.,
SP 233   ``mypackage:templates/foo.pt``.
250c02 234
368746 235 ``renderer_info``
e27808 236   An object implementing the :class:`pyramid.interfaces.IRendererInfo`
eb3394 237   interface.  Basically, an object with the following attributes: ``name``,
ac568b 238   ``package``, and ``type``.
0b4277 239
eb3394 240 ``view``
ac568b 241   The view callable object that was used to render this template.  If the view
SP 242   callable is a method of a class-based view, this will be an instance of the
243   class that the method was defined on.  If the view callable is a function or
244   instance, it will be that function or instance.  Note that this value will
245   only be automatically present when a template is rendered as a result of a
246   ``renderer=`` argument; it will be ``None`` when the ``render_to_response``
247   or ``render`` APIs are used.
eb3394 248
ac568b 249 You can define more values which will be passed to every template executed as a
SP 250 result of rendering by defining :term:`renderer globals`.
c4599b 251
d168a0 252 What any particular renderer does with these system values is up to the
f1aaf1 253 renderer itself, but most template renderers make these names available as
MM 254 top-level template variables.
6ce1e0 255
CM 256 .. index::
257    pair: renderer; templates
250c02 258
9ec2d6 259 .. _templates_used_as_renderers:
CM 260
250c02 261 Templates Used as Renderers via Configuration
CM 262 ---------------------------------------------
2af29e 263
ac568b 264 An alternative to using :func:`~pyramid.renderers.render_to_response` to render
SP 265 templates manually in your view callable code is to specify the template as a
266 :term:`renderer` in your *view configuration*. This can be done with any of the
373b79 267 templating languages supported by :app:`Pyramid`.
2af29e 268
ac568b 269 To use a renderer via view configuration, specify a template :term:`asset
SP 270 specification` as the ``renderer`` argument, or attribute to the :term:`view
271 configuration` of a :term:`view callable`.  Then return a *dictionary* from
272 that view callable.  The dictionary items returned by the view callable will be
273 made available to the renderer template as top-level names.
2af29e 274
ac568b 275 The association of a template as a renderer for a :term:`view configuration`
SP 276 makes it possible to replace code within a :term:`view callable` that handles
277 the rendering of a template.
2af29e 278
ac568b 279 Here's an example of using a :class:`~pyramid.view.view_config` decorator to
SP 280 specify a :term:`view configuration` that names a template renderer:
2af29e 281
CM 282 .. code-block:: python
283    :linenos:
284
197f0c 285    from pyramid.view import view_config
2af29e 286
197f0c 287    @view_config(renderer='templates/foo.pt')
2af29e 288    def my_view(request):
CM 289        return {'foo':1, 'bar':2}
290
7a60e4 291 .. note::
MM 292
ac568b 293    You do not need to supply the ``request`` value as a key in the dictionary
SP 294    result returned from a renderer-configured view callable. :app:`Pyramid`
295    automatically supplies this value for you, so that the "most correct" system
296    values are provided to the renderer.
250c02 297
0b4277 298 .. warning::
CM 299
300    The ``renderer`` argument to the ``@view_config`` configuration decorator
301    shown above is the template *path*.  In the example above, the path
302    ``templates/foo.pt`` is *relative*.  Relative to what, you ask?  Because
303    we're using a Chameleon renderer, it means "relative to the directory in
ac568b 304    which the file that defines the view configuration lives".  In this case,
0b4277 305    this is the directory containing the file that defines the ``my_view``
7a479d 306    function.
0b4277 307
55ce9d 308 Similar renderer configuration can be done imperatively.  See
2033ee 309 :ref:`views_which_use_a_renderer`.
SP 310
311 .. seealso::
312
313     See also :ref:`built_in_renderers`.
250c02 314
0b4277 315 Although a renderer path is usually just a simple relative pathname, a path
CM 316 named as a renderer can be absolute, starting with a slash on UNIX or a drive
ac568b 317 letter prefix on Windows.  The path can alternatively be an :term:`asset
0b4277 318 specification` in the form ``some.dotted.package_name:relative/path``, making
a5ffd6 319 it possible to address template assets which live in another package.
9ec2d6 320
0b4277 321 Not just any template from any arbitrary templating system may be used as a
fd5ae9 322 renderer.  Bindings must exist specifically for :app:`Pyramid` to use a
f1aaf1 323 templating language template as a renderer.
9ec2d6 324
ac568b 325 .. sidebar:: Why Use a Renderer via View Configuration
9ec2d6 326
ac568b 327    Using a renderer in view configuration is usually a better way to render
SP 328    templates than using any rendering API directly from within a :term:`view
329    callable` because it makes the view callable more unit-testable.  Views
330    which use templating or rendering APIs directly must return a
331    :term:`Response` object.  Making testing assertions about response objects
332    is typically an indirect process, because it means that your test code often
333    needs to somehow parse information out of the response body (often HTML).
334    View callables configured with renderers externally via view configuration
335    typically return a dictionary, as above.  Making assertions about results
336    returned in a dictionary is almost always more direct and straightforward
337    than needing to parse HTML.
9ec2d6 338
a7b1a9 339 By default, views rendered via a template renderer return a :term:`Response`
CM 340 object which has a *status code* of ``200 OK``, and a *content-type* of
341 ``text/html``.  To vary attributes of the response of a view that uses a
ac568b 342 renderer, such as the content-type, headers, or status attributes, you must use
SP 343 the API of the :class:`pyramid.response.Response` object exposed as
a7b1a9 344 ``request.response`` within the view before returning the dictionary.  See
CM 345 :ref:`request_response_attr` for more information.
250c02 346
ac568b 347 The same set of system values are provided to templates rendered via a renderer
SP 348 view configuration as those provided to templates rendered imperatively.  See
349 :ref:`renderer_system_values`.
250c02 350
6ce1e0 351 .. index::
CM 352    pair: debugging; templates
353
49d634 354 .. _debugging_templates:
PE 355
488ea0 356 Debugging Templates
CM 357 -------------------
7c525f 358
488ea0 359 A :exc:`NameError` exception resulting from rendering a template with an
16f201 360 undefined variable (e.g. ``${wrong}``) might end up looking like this:
23bfce 361
BL 362 .. code-block:: text
7c525f 363
CM 364     RuntimeError: Caught exception rendering template.
365      - Expression: ``wrong``
fec0f0 366      - Filename:   /home/fred/env/proj/proj/templates/mytemplate.pt
CM 367      - Arguments:  renderer_name: proj:templates/mytemplate.pt
7c525f 368                    template: <PageTemplateFile - at 0x1d2ecf0>
CM 369                    xincludes: <XIncludes - at 0x1d3a130>
370                    request: <Request - at 0x1d2ecd0>
fec0f0 371                    project: proj
7c525f 372                    macros: <Macros - at 0x1d3aed0>
fb6a5c 373                    context: <MyResource None at 0x1d39130>
7c525f 374                    view: <function my_view at 0x1d23570>
CM 375
376     NameError: wrong
377
488ea0 378 The output tells you which template the error occurred in, as well as
7c525f 379 displaying the arguments passed to the template itself.
cc8962 380
0b4277 381 .. index::
CM 382    single: automatic reloading of templates
383    single: template automatic reload
384
385 .. _reload_templates_section:
386
387 Automatically Reloading Templates
388 ---------------------------------
389
ac568b 390 It's often convenient to see changes you make to a template file appear
SP 391 immediately without needing to restart the application process. :app:`Pyramid`
392 allows you to configure your application development environment so that a
393 change to a template will be automatically detected, and the template will be
394 reloaded on the next rendering.
0b4277 395
7a60e4 396 .. warning::
MM 397
ac568b 398    Auto-template-reload behavior is not recommended for production sites as it
SP 399    slows rendering slightly; it's usually only desirable during development.
0b4277 400
CM 401 In order to turn on automatic reloading of templates, you can use an
ac568b 402 environment variable or a configuration file setting.
0b4277 403
ac568b 404 To use an environment variable, start your application under a shell using the
SP 405 ``PYRAMID_RELOAD_TEMPLATES`` operating system environment variable set to
406 ``1``, For example:
23bfce 407
BL 408 .. code-block:: text
0b4277 409
7a60e4 410    $ PYRAMID_RELOAD_TEMPLATES=1 $VENV/bin/pserve myproject.ini
0b4277 411
ac568b 412 To use a setting in the application ``.ini`` file for the same purpose, set the
SP 413 ``pyramid.reload_templates`` key to ``true`` within the application's
414 configuration section, e.g.:
23bfce 415
16cd50 416 .. code-block:: ini
7a60e4 417    :linenos:
0b4277 418
7a60e4 419    [app:main]
MM 420    use = egg:MyProject
421    pyramid.reload_templates = true
0b4277 422
CM 423 .. index::
8c56ae 424    single: template system bindings
b9ce00 425    single: Chameleon
8c56ae 426    single: Jinja2
b9ce00 427    single: Mako
8c56ae 428
853f43 429 .. _available_template_system_bindings:
ba9b0e 430
CM 431 Available Add-On Template System Bindings
432 -----------------------------------------
433
b9ce00 434 The Pylons Project maintains several packages providing bindings to different
MM 435 templating languages including the following:
853f43 436
739fbc 437 +---------------------------+----------------------------+--------------------+
KOP 438 | Template Language         | Pyramid Bindings           | Default Extensions |
439 +===========================+============================+====================+
440 | Chameleon_                | pyramid_chameleon_         | .pt, .txt          |
441 +---------------------------+----------------------------+--------------------+
442 | Jinja2_                   | pyramid_jinja2_            | .jinja2            |
443 +---------------------------+----------------------------+--------------------+
444 | Mako_                     | pyramid_mako_              | .mak, .mako        |
445 +---------------------------+----------------------------+--------------------+
b9ce00 446
MM 447 .. _Chameleon: http://chameleon.readthedocs.org/en/latest/
e85845 448 .. _pyramid_chameleon:
1c561a 449    https://docs.pylonsproject.org/projects/pyramid-chameleon/en/latest/
b9ce00 450
1cb30e 451 .. _Jinja2: http://jinja.pocoo.org/docs/dev/
e85845 452 .. _pyramid_jinja2:
1c561a 453    https://docs.pylonsproject.org/projects/pyramid-jinja2/en/latest/
b9ce00 454
MM 455 .. _Mako: http://www.makotemplates.org/
e85845 456 .. _pyramid_mako:
1c561a 457    https://docs.pylonsproject.org/projects/pyramid-mako/en/latest/