ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 02.01.2026

Просмотров: 2751

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

11. TEMPLATES

5

6

7

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>

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

130

11.6. SIDE EFFECTS OF RENDERING A CHAMELEON 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.

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

11.7 Debugging Templates

A NameError exception resulting from rendering a template with an undefined variable (e.g. ${wrong}) might will end like this:

131



11. TEMPLATES

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 output tells you which template the error occurred in, as well as displaying the arguments passed to the template itself.

11.8 Chameleon Template Internationalization

See Chameleon Template Support for Translation Strings for information about supporting internationalized units of text within Chameleon templates.

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

132


11.10. AUTOMATICALLY RELOADING TEMPLATES

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.

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

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

latex-warning.png

Auto-template-reload behavior is not recommended for production sites as it slows rendering slightly; it’s usually only desirable during development.

133

11. TEMPLATES

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

11.11 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).

134


CHAPTER

TWELVE

VIEW CONFIGURATION

View lookup is the Pyramid subsystem responsible for finding and invoking a view callable. View configuration controls how view lookup operates in your application. During any given request, view configuration information is compared against request data by the view lookup subsystem in order to find the “best” view callable for that request.

In earlier chapters, you have been exposed to a few simple view configuration declarations without much explanation. In this chapter we will explore the subject in detail.

12.1 Mapping a Resource or URL Pattern to a View Callable

A developer makes a view callable available for use within a Pyramid application via view configuration. A view configuration associates a view callable with a set of statements that determine the set of circumstances which must be true for the view callable to be invoked.

A view configuration statement is made about information present in the context resource and the request.

View configuration is performed in one of two ways:

by running a scan against application source code which has a pyramid.view.view_config decorator attached to a Python object as per Adding View Configuration Using the @view_config Decorator.

by using the pyramid.config.Configurator.add_view() method as per Adding View Configuration Using add_view().

135

12. VIEW CONFIGURATION

12.1.1 View Configuration Parameters

All forms of view configuration accept the same general types of arguments.

Many arguments supplied during view configuration are view predicate arguments. View predicate arguments used during view configuration are used to narrow the set of circumstances in which view lookup will find a particular view callable.

View predicate attributes are an important part of view configuration that enables the view lookup subsystem to find and invoke the appropriate view. The greater number of predicate attributes possessed by a view’s configuration, the more specific the circumstances need to be before the registered view callable will be invoked. The fewer number of predicates which are supplied to a particular view configuration, the more likely it is that the associated view callable will be invoked. A view with five predicates will always be found and evaluated before a view with two, for example. All predicates must match for the associated view to be called.

This does not mean however, that Pyramid “stops looking” when it finds a view registration with predicates that don’t match. If one set of view predicates does not match, the “next most specific” view (if any) is consulted for predicates, and so on, until a view is found, or no view can be matched up with the request. The first view with a set of predicates all of which match the request environment will be invoked.

If no view can be found with predicates which allow it to be matched up with the request, Pyramid will return an error to the user’s browser, representing a “not found” (404) page. See Changing the Not Found View for more information about changing the default notfound view.

Other view configuration arguments are non-predicate arguments. These tend to modify the response of the view callable or prevent the view callable from being invoked due to an authorization policy. The presence of non-predicate arguments in a view configuration does not narrow the circumstances in which the view callable will be invoked.

Non-Predicate Arguments

permission The name of a permission that the user must possess in order to invoke the view callable. See Configuring View Security for more information about view security and permissions.

If permission is not supplied, no permission is registered for this view (it’s accessible by any caller).

136