Navigation

Pylons 1.X exposed a module conventionally named helpers.py as an h
object in the top-level namespace of each Mako/Genshi/Jinja2 template which
it rendered. You can emulate the same behavior in Pyramid by using a
BeforeRender event subscriber.

First, create a module named helpers.py in your Pyramid package at the
top level (next to __init__.py). We’ll import the Python standard
library string module to use later in a template:

# helpers.pyimportstring

In the top of the main __init__ module of your Pyramid application
package, import the new helpers module you created, as well as the
BeforeRender event type. Underneath the imports create a function that
will act as an event subscriber:

At this point, with in any view that uses any templating system as a Pyramid
renderer, you will have an omnipresent h top-level name that is a
reference to the helpers module you created. For example, if you have a
view like this:

@view_config(renderer='foo.pt')defaview(request):return{}

In the foo.pt Chameleon template, you can do this:

1

${h.string.uppercase}

The value inserted into the template as the result of this statement will be
ABCDEFGHIJKLMNOPQRSTUVWXYZ (at least if you are using an English system).

You can add more imports and functions to helpers.py as necessary to make
features available in your templates.

You must call the variable this way because of the way Mako works.
It will not know about any other variable other than context until after
%inherit is called. Be aware that context here is not the Pyramid
context in the traversal sense (which is stored in request.context) but
rather the Mako rendering context.

The metal:use-macro="base.macros['base']" statement is essential here.
Content inside <tal:blockmetal:fill-slot="content"></tal:block> tags
will replace corresponding block in base template. You can define
as many slots in as you want. For more information please see
Macro Expansion Template Attribute Language documentation.