pyramid_jinja2 is a set of bindings that make templates written for the Jinja2 templating system work under the Pyramid web framework.
Install using setuptools, e.g. (within a virtualenv):
$ $myvenv/bin/easy_install pyramid_jinja2
Note
If you start a project from scratch, consider using the project template which comes with a working setup and sensible defaults.
There are multiple ways to make sure that pyramid_jinja2 is active. All are completely equivalent:
Use the includeme() function via include():
config = Configurator()
config.include('pyramid_jinja2')
Add pyramid_jinja2 to the list of your pyramid.includes in your .ini settings file:
pyramid.includes =
pyramid_jinja2
If you’re using pyramid_zcml instead of imperative configuration, ensure that some ZCML file with an analogue of the following contents is executed by your Pyramid application:
<include package="pyramid_jinja2"/>
Once activated either of these says, the following happens:
To setup the Jinja2 search path either one of the following steps must be taken:
Add jinja2.directories to your .ini settings file using the pyramid asset spec:
jinja2.directories = yourapp:templates
Or Alternatively by using the add_jinja2_search_path() directive attached to your application’s Configurator instance also using the pyramid asset spec:
config.add_jinja2_search_path("yourapp:templates")
Warning
If you do not explicitly configure your Jinja2 search path it will default to the root of your application. If the specified template is not found in the root of your application and you did not specify a package on the template path it will then try to load the template path relative to the module’s caller package. For example:
Without the search path configured:
@view_config(renderer='templates/mytemplate.jinja2')
With the search path configured:
@view_config(renderer='mytemplate.jinja2')
If you view module is in app.module.view and your template is under app/module/templates/mytemplate.jinja2 you can access that asset in a few different ways.
Using the full path:
@view_config(renderer="module/templates/mytemplate.jinja2")
Using the package:
@view_config(renderer="app.module:templates/mytemplate.jinja2")
Using the relative path to current package:
@view_config(renderer="templates/mytemplate.jinja2")
You need to be careful when using relative paths though, if there is an app/templates/mytemplate.jinja2 this will be used instead as Jinja2 lookup will first try the path relative to the root of the app and then it will try the path relative to the current package.
Finally, to make sure your .jinja2 template files are included in your package’s source distribution (e.g. when using python setup.py sdist), add *.jinja2 to your MANIFEST.in:
recursive-include yourapp *.ico *.png *.css *.gif *.jpg *.pt *.txt *.mak *.mako *.jinja2 *.js *.html *.xml
Once pyramid_jinja2 been activated .jinja2 templates can be loaded either by looking up names that would be found on the Jinja2 search path or by looking up asset specifications.
The default lookup mechanism for templates uses the Jinja2 search path (specified with jinja2.directories or by using the add_jinja2_search_path() directive on the Configurator instance).
Rendering Jinja2 templates with a view like this is typically done as follows (where the templates directory is expected to live in the search path):
1 2 3 4 5 | from pyramid.view import view_config
@view_config(renderer='mytemplate.jinja2')
def myview(request):
return {'foo':1, 'bar':2}
|
Rendering templates outside of a view (and without a request) can be done using the renderer api:
1 2 | from pyramid.renderers import render_to_response
render_to_response('mytemplate.jinja2', {'foo':1, 'bar':2})
|
Template inheritance can use asset specs in the same manner as regular template lookups. An example:
1 2 3 4 5 6 7 8 9 10 11 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<!-- templates/layout.jinja2 -->
<html lang="en">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
</body>
|
1 2 3 4 5 6 7 8 | <!-- templates/root.jinja2 -->
{% extends "templates/layout.jinja2" %}
{% block content %}
<h1>Yes</h1>
<p>
Some random paragraph.
</p>
{% endblock %}
|
For further information on Template Inheritance in Jinja2 templates please see Template Inheritance in Jinja2 documentation.
Looking up templates via asset specification is a feature specific to Pyramid. For further info please see Understanding Asset Specifications. Overriding templates in this style uses the standard pyramid asset overriding technique.
When pyramid_jinja2 is included as pyramid application, jinja2.ext.i18n is automatically activated.
Be sure to configure jinja2.i18n.domain according to setup.cfg domain settings. By default, jinja2.i18n.domain is set to the package name of the pyramid application.
Jinja2 derives additional settings to configure its template renderer. Many of these settings are optional and only need to be set if they should be different from the default. The below values can be present in the .ini file used to configure the Pyramid application (in the app section representing your Pyramid app) or they can be passed directly within the settings argument passed to a Pyramid Configurator.
These setttings correspond to the ones documented in Jinja2. Set them accordingly.
For reference please see: http://jinja.pocoo.org/docs/api/#high-level-api
Note
For the boolean settings please use true or false
jinja2.block_start_string
jinja2.block_end_string
jinja2.variable_start_string
jinja2.variable_end_string
jinja2.comment_start_string
jinja2.comment_end_string
jinja2.line_statement_prefix
jinja2.line_comment_prefix
jinja2.trim_blocks
jinja2.newline_sequence
jinja2.optimized
jinja2.cache_size
Jinja2 autoescape setting.
Possible values: true or false.
Warning
By default Jinja2 sets autoescaping to False.
pyramid_jinja2 sets it to true as it is considered a good security practice.
This is a Pyramid setting (not a pyramid_jinja2 one)
For usage see Pyramid: Automatically Reloading Templates.
true or false representing whether Jinja2 templates should be reloaded when they change on disk. Useful for development to be true. This setting sets to Jinja2 auto_reload setting.
The rationale for using is a differently named setting is: this setting existed when Pyramid only supported Chameleon and Mako templates and acts uniformly across the template renderers.
Warning
Deprecated as of version 1.5, use pyramid.reload_templates instead
Use Pyramid pyramid.reload_templates setting.
A list of directory names or a newline-delimited string with each line representing a directory name. These locations are where Jinja2 will search for templates. Each can optionally be an absolute resource specification (e.g. package:subdirectory/).
The input encoding of templates. Defaults to utf-8.
Changes the undefined types that are used when a variable name lookup fails. If unset, defaults to Undefined (silent ignore). Setting it to strict will trigger StrictUndefined behavior (raising an error, this is recommended for development). Setting it to debug will trigger DebugUndefined, which outputs debug information in some cases. See Undefined Types
A list of extension objects or a newline-delimited set of dotted import locations where each line represents an extension. jinja2.ext.i18n is automatically activated.
Pyramid domain for translations. See Translation Domain in Pyramid documentation. Defaults to the package name of the pyramid application.
A dictionary mapping filter name to filter object, or a newline-delimted string with each line in the format:
name = dotted.name.to.filter
representing Jinja2 filters.
A dictionary mapping global name to global template object, or a newline-delimited string with each line in the format:
name = dotted.name.to.globals
representing Jinja2 globals
A dictionary mapping test name to test object, or a newline-delimted string with each line in the format:
name = dotted.name.to.test
representing Jinja2 tests.
true or false to enable filesystem bytecode caching. Defaults to true. See Bytecode Cache in Jinja2 documentation.
Absolute path to directory to store bytecode caching files. Defaults to temporary directory. See jinja2.FileSystemBytecodeCache.
Note
pyramid_jinja2 will attempt to delete the cached files by calling jinja2.BytecodeCache.clear() from function registered by atexit.register().
Warning
As noted by the atexit documentation the functions registered by the module will only be called upon normal termination. In case of abnormal program termination the files may remain, littering your file system (and eating up inodes).
You are strongly advised to consider an additional clean up strategy (such as cron) to check and remove such files.
true or false to enable the use of newstyle gettext calls. Defaults to false.
See Newstyle Gettext http://jinja.pocoo.org/docs/extensions/#newstyle-gettext
pyramid_jinja2 provides following filters.
A filter from model to a string representing the absolute URL. This filter calls pyramid.url.resource_url().
A filter from route_name to a string representing the absolute URL. This filter calls pyramid.url.route_url().
A filter from path to a string representing the absolute URL. This filter calls pyramid.url.static_url().
A filter from route_name to a string representing the relative URL. This filter calls pyramid.url.route_path().
A filter from path to a string representing the relative URL. This filter calls pyramid.url.static_path().
To use these filters, configure the settings of jinja2.filters:
1 2 3 4 5 6 | [app:yourapp]
# ... other stuff ...
jinja2.filters =
model_url = pyramid_jinja2.filters:model_url_filter
route_url = pyramid_jinja2.filters:route_url_filter
static_url = pyramid_jinja2.filters:static_url_filter
|
And use the filters in template.
<a href="{{context|model_url('edit')}}">Edit</a>
<a href="{{'top'|route_url}}">Top</a>
<link rel="stylesheet" href="{{'yourapp:static/css/style.css'|static_url}}" />
After you’ve got pyramid_jinja2 installed, you can invoke one of the following commands to create a Jinja2-based Pyramid project.
On Pyramid 1.0, 1.1, or 1.2:
$ $myvenv/bin/paster create -t pyramid_jinja2_starter myproject
On Pyramid 1.3:
$ $myenv/bin/pcreate -s pyramid_jinja2_starter myproject
After it’s created, you can visit the myproject directory and run setup.py develop. At that point you can start the application like any other Pyramid application.
This is a good way to see a working Pyramid application that uses Jinja2, even if you wind up not using the result.
The paster template automatically sets up pot/po/mo locale files for use with the generated project.
The usual pattern for working with i18n in pyramid_jinja2 is as follows:
1 2 3 4 5 6 7 8 9 10 | # make sure Babel is installed
easy_install Babel
# extract translatable strings from *.jinja2 / *.py
python setup.py extract_messages
python setup.py update_catalog
# Translate strings in <mypackage>/locale/<mylocale>/LC_MESSAGES/<myproject>.po
# and re-compile *.po files
python setup.py compile_catalog
|
Visit http://github.com/Pylons/pyramid_jinja2 to download development or tagged versions.
Visit http://github.com/Pylons/pyramid_jinja2/issues to report bugs.