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