35
pyramid 2 Release 2.3.3 Repoze Developers April 16, 2015

pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛Release 2.3.3

Repoze Developers

April 16, 2015

Page 2: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer
Page 3: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

Contents

1 Overview 1

2 Installation 3

3 Setup 53.1 Preparing for distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

4 Usage 74.1 Template Lookup Mechanisms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74.2 Adding or Overriding a Renderer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94.3 Internalization (i18n) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

5 Settings 115.1 Generic Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115.2 jinja2.autoescape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115.3 pyramid.reload_templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125.4 reload_templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125.5 jinja2.auto_reload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125.6 jinja2.directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125.7 jinja2.input_encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125.8 jinja2.undefined . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125.9 jinja2.extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135.10 jinja2.i18n.domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135.11 jinja2.filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135.12 jinja2.globals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135.13 jinja2.tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135.14 jinja2.bytecode_caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135.15 jinja2.bytecode_caching_directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145.16 jinja2.newstyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

6 Jinja2 Filters 15

7 Creating a Jinja2 Pyramid Project 177.1 Paster Template I18N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

8 More Information 198.1 pyramid_jinja2 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198.2 Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208.3 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

i

Page 4: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

9 Reporting Bugs / Development Versions 279.1 Indices and tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Python Module Index 29

ii

Page 5: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

CHAPTER 1

Overview

pyramid_jinja2 is a set of bindings that make templates written for the Jinja2 templating system work under thePyramid web framework.

1

Page 6: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

2 Chapter 1. Overview

Page 7: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

CHAPTER 2

Installation

Install using setuptools, e.g. (within a virtualenv):

$ $VENV/bin/easy_install pyramid_jinja2

3

Page 8: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

4 Chapter 2. Installation

Page 9: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

CHAPTER 3

Setup

Note: If you start a project from scratch, consider using the project template which comes with a working setup andsensible defaults.

There are multiple ways to make sure that pyramid_jinja2 is active. All are completely equivalent:

1. Use the includeme() function via include():

config = Configurator()config.include(’pyramid_jinja2’)

2. Add pyramid_jinja2 to the list of your pyramid.includes in your .ini settings file:

pyramid.includes =pyramid_jinja2

3. If you’re using pyramid_zcml instead of imperative configuration, ensure that some ZCML file with an analogueof the following contents is executed by your Pyramid application:

<include package="pyramid_jinja2"/>

Once activated either of these says, the following happens:

1. Files with the .jinja2 extension are considered to be Jinja2 templates and a jinja2.Environment isregistered to handle this extension.

2. The pyramid_jinja2.add_jinja2_renderer() directive is added to the Configurator instance.

3. The pyramid_jinja2.add_jinja2_search_path() directive is added to the Configurator instance.

4. The pyramid_jinja2.add_jinja2_extension() directive is added to the Configurator instance.

5. The pyramid_jinja2.get_jinja2_environment() directive is added to the Configurator instance.

3.1 Preparing for distribution

If you want to make sure your .jinja2 template files are included in your package’s source distribution (e.g. whenusing 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

5

Page 10: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

6 Chapter 3. Setup

Page 11: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

CHAPTER 4

Usage

Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system.

When used as the renderer argument of a view, the view must return a Python dict which will be passed into thetemplate as the set of available variables.

4.1 Template Lookup Mechanisms

There are several ways to configure pyramid_jinja2 to find your templates.

4.1.1 Asset Specifications

Templates may always be defined using an asset specification. These are strings which define an absolute location ofthe template relative to some Python package. For example myapp.views:templates/home.jinja2. Thesespecifications are supported throughout Pyramid and provide a fool-proof way to find any supporting assets bundledwith your application.

Here’s an example view configuration which uses an asset specification:

1 @view_config(renderer=’mypackage:templates/foo.jinja2’)2 def hello_world(request):3 return {’a’: 1}

Asset specifications have some significant benefits in Pyramid, as they are fully overridable. An addon package canship with code that renders using asset specifications. Later another package can externally override the templateswithout having to actually modify the addon in any way. See Overriding Assets for more information.

4.1.2 Caller-Relative Template Lookup

By default, templates are discovered relative to the caller’s package. This means that if you define a view in a Pythonmodule, the templates would be found relative to the module’s directory on the filesystem.

Let’s look at an example:

1 @view_config(renderer=’templates/mytemplate.jinja2’)2 def my_view(request):3 return {’foo’: 1, ’bar’: 2}

Imagine that the above code is in a myapp.admin.views module. The template would be relative to that moduleon the filesystem, as shown below:

7

Page 12: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

myapp|- __init__.py‘- admin

|- views.py‘- templates

|- base.jinja2‘- mytemplate.jinja2

Caller-relative lookup avoids naming collisions which can be common in a search path-based approach.

A caller-relative template lookup is converted to a asset specification underneath the hood. Thismeans that it’s almost always possible to override the actual template in an addon package withouthaving to fork the addon itself. For example, the full asset spec for the view above would bemyapp.admin.views:templates/mytemplate.jinja2. This template, or the entire templates foldermay be overridden.

config.override_asset(to_override=’myapp.admin.views:templates/mytemplate.jinja2’,override_with=’yourapp:templates/sometemplate.jinja2’)

See Overriding Assets for more information.

4.1.3 Search Path-Based Template Lookup

When used outside of Pyramid, Jinja2’s default lookup mechanism is a search path. To use a search path within Pyra-mid, simply define the jinja2.directories configuration setting or use the add_jinja2_search_path()configurator directive.

Rendering Jinja2 templates with a search path is typically done as follows:

@view_config(renderer=’mytemplate.jinja2’)def my_view(request):

return {’foo’: 1, ’bar’: 2}

If mytemplate.jinja2 is not found in the same directory as the module then it will be searched for on the searchpath. We are now dependent on our configuration settings to tell us where the template may be located. Commonlya templates directory is created at the base of the package and the configuration file will include the followingdirective:

jinja2.directories = mypkg:templates

Warning: It is possible to specify a relative path to the templates folder, such as jinja2.directories= templates. This folder will be found relative to the first package that includes pyramid_jinja2, which willnormally be the root of your application. It is always better to be explicit when in doubt.

Note: The package that includes pyramid_jinja2 will always be added to the search path (in most cases this is top-level package in your application). This behavior may be deprecated or removed in the future, it is always better tospecify your search path explicitly.

4.1.4 Templates Including Templates

Jinja2 allows template inheritance as well as other mechanisms for templates to load each other. The lookup mech-anisms supported in these cases include asset specifications, template-relative names and normal template namesfound on the search path. The search path will always be consulted if a template cannot be found relative to the

8 Chapter 4. Usage

Page 13: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

parent template. For example if you had a template named templates/child.jinja2 that wanted to extendtemplates/base.jinja2 then it could use {% extends ’base.jinja2’ %} and locate the file relativeto itself or it could use {% extends ’templates/base.jinja2’ %} to find the template in a templatessubfolder rooted on the search path. The template-relative option will always override the search path.

An example:

1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">2 <!-- templates/layout.jinja2 -->3

4 <html lang="en">5 <html xmlns="http://www.w3.org/1999/xhtml">6 <head>7 <link rel="stylesheet" href="style.css" />8 </head>9 <body>

10 <div id="content">{% block content %}{% endblock %}</div>11 </body>

1 <!-- templates/root.jinja2 -->2 {% extends "templates/layout.jinja2" %}3 {% block content %}4 <h1>Yes</h1>5 <p>6 Some random paragraph.7 </p>8 {% endblock %}

For further information on Template Inheritance in Jinja2 templates please see Template Inheritance in Jinja2 docu-mentation.

4.2 Adding or Overriding a Renderer

By default, only templates ending in the .jinja2 file extension are supported. However, it is very easy to addsupport for alternate file extensions using the pyramid_jinja2.add_jinja2_renderer() directive.

config.include(’pyramid_jinja2’)config.add_jinja2_renderer(’.html’)

It would now be possible to use templates named foo.html and foo.jinja2. Each renderer extension will useits own jinja2.Environment. These alternate renderers can be extended at runtime using the name parameterto the other directives such as pyramid_jinja2.get_jinja2_environment().

config.include(’pyramid_jinja2’)config.add_jinja2_renderer(’.html’)config.add_jinja2_search_path(’myapp:templates’, name=’.html’)

It is also possible to setup different renderers that use different search paths, configuration settings and environ-ments if necessary. This technique can come in handy when different defaults are required for rendering tem-plates with different content types. For example, a plain text email body versus an html page. For this reason,pyramid_jinja2.add_jinja2_renderer() accepts an optional parameter settings_prefixwhich canpoint a renderer at a different group of settings.

settings = {’jinja2.directories’: ’myapp:html_templates’,’mail.jinja2.directories’: ’myapp:email_templates’,

}

4.2. Adding or Overriding a Renderer 9

Page 14: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

config = Configurator(settings=settings)config.include(’pyramid_jinja2’)config.add_jinja2_renderer(’.email’, settings_prefix=’mail.jinja2.’)

Now foo.email will be rendered using the mail.jinja2.* settings.

4.3 Internalization (i18n)

When pyramid_jinja2 is included in a 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 setto the name of the package that included pyramid_jinja2. If no package was found, it will use messages.

10 Chapter 4. Usage

Page 15: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

CHAPTER 5

Settings

Jinja2 derives additional settings to configure its template renderer. Many of these settings are optional and only needto be set if they should be different from the default. The below values can be present in the .ini file used to configurethe Pyramid application (in the app section representing your Pyramid app) or they can be passed directly within thesettings argument passed to a Pyramid Configurator.

5.1 Generic Settings

These settings 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

5.2 jinja2.autoescape

Jinja2 autoescape setting.

Possible values: true or false.

11

Page 16: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

Warning: By default Jinja2 sets autoescaping to False.pyramid_jinja2 sets it to true as it is considered a good security practice in a web setting where we want to preventXSS attacks from rendering unsanitized user-generated content. To turn off escaping on a case-by-case basis youmay use the safe filter such as {{ html_blob | safe }}.

5.3 pyramid.reload_templates

For usage see Pyramid: Automatically Reloading Templates.

true or false representing whether Jinja2 templates should be reloaded when they change on disk. Useful fordevelopment to be true. This setting sets the Jinja2 auto_reload setting.

5.4 reload_templates

Warning: Deprecated as of version 1.5, use pyramid.reload_templates instead

5.5 jinja2.auto_reload

Use Pyramid pyramid.reload_templates setting.

5.6 jinja2.directories

A list of directory names or a newline-delimited string with each line representing a directory name. These loca-tions are where Jinja2 will search for templates. Each can optionally be an absolute resource specification (e.g.package:subdirectory/).

5.7 jinja2.input_encoding

The input encoding of templates. Defaults to utf-8.

5.8 jinja2.undefined

Changes the undefined types that are used when a variable name lookup fails. If unset, defaults to Undefined (silentignore). Setting it to strict will trigger StrictUndefined behavior (raising an error, this is recommended fordevelopment). Setting it to debug will trigger DebugUndefined, which outputs debug information in some cases.See Undefined Types

12 Chapter 5. Settings

Page 17: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

5.9 jinja2.extensions

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.

5.10 jinja2.i18n.domain

Pyramid domain for translations. See Translation Domain in Pyramid documentation. Defaults to the name of thepackage that activated pyramid_jinja2 or if that fails it will use messages as the domain.

5.11 jinja2.filters

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.

5.12 jinja2.globals

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

5.13 jinja2.tests

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.

5.14 jinja2.bytecode_caching

If set to true, a filesystem bytecode cache will be configured (in a directory determined byjinja2.bytecode_caching_directory.) To configure other types of bytecode caching, jinja2.bytecode_cachingmay also be set directly to an instance of jinja2.BytecodeCache (This can not be done in a paste .ini file,however, it must be done programatically.) By default, no bytecode cache is configured.

Changed in version 1.10: Previously, jinja2.bytecode_caching defaulted to true.

Note that configuring a filesystem bytecode cache will (not surprisiningly) generate files in the cache directory. Astemplates are changed, some of these will become stale, pointless wastes of disk space. You are advised to consider aclean up strategy (such as a cron job) to check for and remove such files.

See the Jinja2 Documentation for more information on bytecode caching.

5.9. jinja2.extensions 13

Page 18: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

Changed in version 1.10: Previously, an atexit callback which called jinja2.BytecodeCache.clear() wasregistered in an effort to delete the cache files. This is no longer done.

5.15 jinja2.bytecode_caching_directory

Absolute path to directory to store bytecode cache files. Defaults to the system temporary directory. This is only usedif jinja2.bytecode_caching is set to true.

5.16 jinja2.newstyle

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

14 Chapter 5. Settings

Page 19: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

CHAPTER 6

Jinja2 Filters

pyramid_jinja2 provides following filters.

pyramid_jinja2.filters.model_url_filter(ctx, model, *elements, **kw)A filter from model to a string representing the absolute URL. This filter callspyramid.url.resource_url().

pyramid_jinja2.filters.route_url_filter(ctx, route_name, *elements, **kw)A filter from route_name to a string representing the absolute URL. This filter callspyramid.url.route_url().

pyramid_jinja2.filters.static_url_filter(ctx, path, **kw)A filter from path to a string representing the absolute URL. This filter callspyramid.url.static_url().

pyramid_jinja2.filters.route_path_filter(ctx, route_name, *elements, **kw)A filter from route_name to a string representing the relative URL. This filter callspyramid.url.route_path().

pyramid_jinja2.filters.static_path_filter(ctx, path, **kw)A filter from path to a string representing the relative URL. This filter callspyramid.url.static_path().

To use these filters, configure the settings of jinja2.filters:

1 [app:yourapp]2 # ... other stuff ...3 jinja2.filters =4 model_url = pyramid_jinja2.filters:model_url_filter5 route_url = pyramid_jinja2.filters:route_url_filter6 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}}" />

15

Page 20: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

16 Chapter 6. Jinja2 Filters

Page 21: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

CHAPTER 7

Creating a Jinja2 Pyramid Project

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:

$ $VENV/bin/paster create -t pyramid_jinja2_starter myproject

On Pyramid 1.3+:

$ $VENV/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 startthe 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.

7.1 Paster Template I18N

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 # make sure Babel is installed2 easy_install Babel3

4 # extract translatable strings from *.jinja2 / *.py5 python setup.py extract_messages6 python setup.py update_catalog7

8 # Translate strings in <mypackage>/locale/<mylocale>/LC_MESSAGES/<myproject>.po9 # and re-compile *.po files

10 python setup.py compile_catalog

17

Page 22: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

18 Chapter 7. Creating a Jinja2 Pyramid Project

Page 23: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

CHAPTER 8

More Information

8.1 pyramid_jinja2 API

pyramid_jinja2.includeme(config)Set up standard configurator registrations. Use via:

config = Configurator()config.include(’pyramid_jinja2’)

Once this function has been invoked, the .jinja2 renderer is available for use in Pyramid and these newdirectives are available as methods of the configurator:

•add_jinja2_renderer: Add a new Jinja2 renderer, with a different file extension and/or settings.

•add_jinja2_search_path: Add a new location to the search path for the specified renderer.

•add_jinja2_extension: Add a list of extensions to the Jinja2 environment used by the specifiedrenderer.

•get_jinja2_environment: Return the jinja2.Environment used by the specified renderer.

pyramid_jinja2.add_jinja2_renderer(config, name, settings_prefix=’jinja2.’, package=None)This function is added as a method of a Configurator, and should not be called directly. Instead it should becalled like so after pyramid_jinja2 has been passed to config.include:

config.add_jinja2_renderer(’.html’, settings_prefix=’jinja2.’)

It will register a new renderer, loaded from settings at the specified settings_prefix prefix. This rendererwill be active for files using the specified extension name.

pyramid_jinja2.add_jinja2_search_path(config, searchpath, name=’.jinja2’, prepend=False)This function is added as a method of a Configurator, and should not be called directly. Instead it should becalled like so after pyramid_jinja2 has been passed to config.include:

config.add_jinja2_search_path(’anotherpackage:templates/’)

It will add the directory or asset specification passed as searchpath to the current search path of thejinja2.Environment used by the renderer identified by name.

By default the path is appended to the end of the search path. If prepend is set to True then the path will beinserted at the start of the search path.

pyramid_jinja2.add_jinja2_extension(config, ext, name=’.jinja2’)This function is added as a method of a Configurator, and should not be called directly. Instead it should becalled like so after pyramid_jinja2 has been passed to config.include:

19

Page 24: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

config.add_jinja2_extension(myext)

It will add the Jinja2 extension passed as ext to the current jinja2.Environment used by the renderernamed name.

pyramid_jinja2.get_jinja2_environment(config, name=’.jinja2’)This function is added as a method of a Configurator, and should not be called directly. Instead it should becalled like so after pyramid_jinja2 has been passed to config.include:

config.get_jinja2_environment()

It will return the configured jinja2.Environment for the renderer named name. Configuration is delayeduntil a call to config.commit() or config.make_wsgi_app(). As such, if this method is called priorto committing the changes, it may return None.

class pyramid_jinja2.Jinja2TemplateRenderer(template_loader)Renderer for a jinja2 template

class pyramid_jinja2.SmartAssetSpecLoader(searchpath=(), encoding=’utf-8’, debug=False)A Jinja2 template loader that knows how to handle asset specifications.

8.2 Changes

8.2.1 2.3.3 (2014-07-01)

• #91: Fix a recursion error while attempting to include a template with the same name as one of the parents thatwas already loaded. [mmerickel]

8.2.2 2.3.2 (2014-06-13)

• Fix 2.3.1 brownbag release. It had some erroneous didn’t-mean-to-push changes that are now solved. Broughtcoverage back up to 100%.

8.2.3 2.3.1 (2014-06-13)

• Improve the template-relative searchpath logic to search more possibilities in the include-chain built up fromtemplates including or extending other templates. The logic for when the chain was longer than just one templateincluding another template was broken.

8.2.4 2.3 (2014-05-30)

• Require pyramid_jinja2 to be included even when using pyramid_jinja2.renderer_factory. Itis now a thin wrapper around the default renderer and can be used to share the same settings with another fileextension. [mmerickel]

Backward Incompatible Changes

• pyramid_jinja2 must be included into the Configurator in order to usepyramid_jinja2.renderer_factory otherwise you may see the exception:

20 Chapter 8. More Information

Page 25: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

ValueError: As of pyramid_jinja2 2.3, the use of the"pyramid_jinja2.renderer_factory" requires that pyramid_jinja2 beconfigured via config.include("pyramid_jinja2") or the equivalent"pyramid.includes" setting.

The fix is to include pyramid_jinja2:

config.include(’pyramid_jinja2’)

8.2.5 2.2 (2014-05-30)

• #88: Formalize template loading order and allow all lookups to fallback to the search path. A template is nowalways searched for relative to its parent template. If not found, the lookup will fallback to the search path.[mmerickel]

• Add prepend option to config.add_jinja2_search_path to allow prepending of paths to the begin-ning of the search path if a path should override previously defined paths. [mmerickel]

8.2.6 2.1 (2014-05-16)

• The 2.0 series started adding the package that invoked config.add_jinja2_renderer to the templatesearch path. This is being removed in favor of explicit search paths and will hopefully not affect many peopleas it has only been available for a couple weeks. The only automatic search path left is the one added by thedefault .jinja2 renderer created when including pyramid_jinja2. [mmerickel]

• Adjust the config.include(’pyramid_jinja2’) to add any packages fromjinja2.directories before the default search path at the base of the app. Previously there wasno way to override that search path. [mmerickel]

8.2.7 2.0.2 (2014-05-06)

• The path of the child template is always considered when inheriting from a base template. Therefore when doingrender(’templates/foo.jinja2’) and foo.jinja2 has an {% extends ’base.jinja2’%}, the template will be searched for as ’templates/base.jinja2’ on the search path. Previouslythe path of the child template was ignored when doing the lookup for the base, causing some very subtle andunrecoverable lookup errors when the child template was found relative to the caller instead of being found onthe search path. [mmerickel]

• This release restores the default search path behaviors from the 1.x series that were inadvertently removed in the2.x. The project’s root package is added to the search path by default. [mmerickel]

8.2.8 2.0.1 (2014-04-23)

• #86: Fix a regression caused by the new support for extending a template relative to itself. Using {% extends’some_asset:spec.jinja2’ %} was no longer working and is now fixed. [mmerickel]

8.2.9 2.0 (2014-04-21)

• Claim Python 3.4 support [mmerickel]

• #75: Fix the missing piece of relative template loading by allowing a template to inherit from a template relativeto itself, instead of forcing the parent to be on the search path. [mmerickel]

8.2. Changes 21

Page 26: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

• #73: Added a new config.add_jinja2_renderer API that can create and override multiple Jinja2renderers, each loaded using potentially different settings and extensions.

The other APIs are now keyed on the renderer extension, as each extension may have differentsettings. Thus config.add_jinja2_search_path, config.add_jinja2_extension, andconfig.get_jinja2_environment accept a name argument, which defaults to .jinja2.

This deprecates the old pyramid_jinja2.renderer_factory mechanism for adding renderers withalternate extensions.

Configuration of the renderers has been updated to follow Pyramid’s standard mechanisms for conflict detec-tion. This means that if two modules both try to add a renderer for the .jinja2 extension, they may raise aconflict or the modifications made by the invocation closest to the Configurator in the call-stack will win.This behavior can be affected by calling config.commit at appropriate times to force a configuration totake effect immediately. As such, configuration is deferred until commit-time, meaning that it is now possibleconfig.get_jinja2_environment will return None because the changes have not yet been committed.[mmerickel]

Backward Incompatible Changes

• The creation and configuration of the Jinja2 Environment is now deferred until commit-type in the PyramidConfigurator. This means that config.get_jinja2_environment may return None. To resolvethis, invoke config.commit() before attempting to get the environment.

8.2.10 1.10 (2014-01-11)

• #77: Change semantics of jinja2.bytecode_caching setting. The new default is false (no bytecodecaching) — bytecode_caching must explicitly be set to true to enable a filesystem bytecode cache. Inaddition, an atexit callback to clean the cache is no longer registered (as this seemed to defeat most of thepurpose of having a bytecode cache.) Finally, a more complex bytecode cache may be configured by settingjinja2.bytecode_caching directly to a jinja2.BytecodeCache instance. (This can not be donein a paste .ini file, it must be done programatically.) [dairiki]

• prevent error when using python setup.py bdist_wheel [msabramo]

8.2.11 1.9 (2013-11-08)

• fix indentation level for Jinja2ProjectTemplate in scaffolds/__init__.py [Bruno Binet]

• Remove unnecessary dependency on pyramid.interfaces.ITemplateRenderer which was depre-cated in Pyramid 1.5. [mmerickel]

• #68: Added model_path_filter, route_path_filter and static_path_filter filters [Remco]

• #74: Fixed issue with route being converted as_const by jinja2 engine when using btyecode cache [Remco]

8.2.12 1.8 (2013-10-03)

• #70: Do not pin for py3.2 compatibility unless running under py3.2 [dairiki]

22 Chapter 8. More Information

Page 27: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

8.2.13 1.7 (2013-08-07)

• #56: python3.3: Non-ASCII characters in changelog breaks pip installation [Domen Kožar]

• #57: Remove useless warning: DeprecationWarning: reload_templates setting is deprecated, use pyra-mid.reload_templates instead. [Marc Abramowitz]

8.2.14 1.6 (2013-01-23)

• Set jinja2.i18n.domain default to the package name of the pyramid application. [Domen Kožar]

• Add jinja2.globals setting to add global objects into the template context [Eugene Fominykh]

• Add jinja2.newstyle setting to enable newstyle gettext calls [Thomas Schüßler]

8.2.15 1.5 (2012-11-24)

• Add pyramid.reload_templates to set jinja2.auto_reload instead of using reload_templates. Deprecate the latter.[Domen Kožar]

• Clear bytecode cache on atexit [Domen Kožar]

• Add support for more Jinja2 options. Note support for jinja2.autoescape is limited to boolean only.

– 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

[Michael Ryabushkin]

8.2.16 1.4.2 (2012-10-17)

• Add jinja2.undefined setting to change handling of undefined types. [Robert Buchholz]

• Remove redundant decoding error handling [Domen Kožar]

• Configure bytecode caching by default. Introduce jinja2.bytecode_caching andjinja2.bytecode_caching_directory settings. [Domen Kožar]

• Allow to add custom Jinja2 tests in jinja2.tests setting. [Sebastian Kalinowski]

8.2. Changes 23

Page 28: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

8.2.17 1.4.1 (2012-09-12)

• Fix brown-bag release [Domen Kožar]

8.2.18 1.4 (2012-09-12)

• Correctly resolve relative search paths passed to add_jinja2_search_path andjinja2.directories [Domen Kožar]

• #34: Don’t recreate jinja2.Environment for add_jinja2_extension [Domen Kožar]

• Drop Python 2.5 compatibility [Domen Kožar]

• Addition of static_url filter.

• Add dev and docs setup.py aliases (ala Pyramid).

• Changed template loading relative to package calling the renderer so it works like the Chameleon templateloader.

8.2.19 1.3 (2011-12-14)

• Make scaffolding compatible with Pyramid 1.3a2+.

8.2.20 1.2 (2011-09-27)

• Make tests pass on Pyramid 1.2dev.

• Make compatible with Python 3.2 (requires Pyramid 1.3dev+).

8.2.21 1.1 (2011-07-24)

• Add get_jinja2_environment directive.

• Add all configurator directives to documentation.

8.2.22 1.0 (2011-05-12)

• Message domain can now be specified with jinja2.i18n.domain for i18n

• Paster template now sets up starter locale pot/po/mo files

• pyramid_jinja2 now depends on Jinja2 >= 2.5.0 due to jinja2.Environment.install_gettext_callablesuse https://github.com/Pylons/pyramid_jinja2/pull/21

• Added demo app just to visualize i18n work

8.2.23 0.6.2 (2011-04-06)

• jinja2.ext.i18n is now added by default, see i18n.rst for details

• Added add_jinja2_extension directive to the Configurator

• Updated jinja2.extensions parsing mechanism

24 Chapter 8. More Information

Page 29: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

• Fixed docs to indicate using asset: prefix is no longer necessary

8.2.24 0.6.1 (2011-03-03)

• Asset-based loading now takes precedance and does not require “asset:” prefix

• Fixed the “current” package mechanism of asset: loading so that it more accurately finds the current package

• Dependency on pyramid_zcml removed.

8.2.25 0.6 (2011-02-15)

• Documentation overhauled.

• Templates can now be looked up by asset spec completely bypassing the search path by specifying a prefix ofasset:.

• Updated paster template to more closely relate to changes made to paster templmates in Pyramid core.

• Add new directive add_jinja2_search_path to the configurator when includeme is used.

8.2.26 0.5 (2011-01-18)

• Add includeme function (meant to be used via config.include).

• Fix documentation bug related to paster create reported at https://github.com/Pylons/pyramid_jinja2/issues#issue/12

• Depend upon Pyramid 1.0a10 + (to make ZCML work).

8.2.27 0.4 (2010-12-16)

Paster Template

• Changes to normalize with default templates shipping with Pyramid core: remove calls to config.begin()and config.end() from __init__.main, entry point name changed to main, entry __init__.pyfunction name changed to main, depend on WebError, use paster_plugins argument to setup function insetup.py, depend on Pyramid 1.0a6+ (use config rather than configurator).

Tests

• Use testing.setUp and testing.tearDown rather than constructing a Configurator (better fwd com-pat).

Features

• Add model_url and route_url filter implementations (and documented).

Documentation

• Use Makefile which pulls in Pylons theme automagically.

8.2. Changes 25

Page 30: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

8.2.28 0.3 (2010-11-26)

• Add jinja2.filters and jinja2.extensions settings (thanks to aodag).

• Document all known settings.

8.2.29 0.2 (2010-11-06)

• Template autoreloading did not function, even if reload_templates was set to True.

8.2.30 0.1 (2010-11-05)

• First release. Not backwards compatible with repoze.bfg.jinja2: we use a filesystem loader (the directo-ries to load from come from the jinja2.directories setting). No attention is paid to the current packagewhen resolving a renderer= line.

8.3 Glossary

Asset Specification A string representing the path to a directory or file present in a Python module. See Understand-ing Asset Specifications in the Pyramid documentation for more information.

Configurator pyramid.config.Configurator

Jinja2 A templating system written by Armin Ronacher.

Pyramid A web framework.

pyramid_jinja2 A set of bindings that make templates written for the Jinja2 templating system work under thePyramid web framework.

Template Inheritance Allows you to build a base “skeleton” template that contains all the common elements of yoursite and defines blocks that child templates can override. See Template Inheritance in the Jinja2 documentation.

26 Chapter 8. More Information

Page 31: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

CHAPTER 9

Reporting Bugs / Development Versions

Visit http://github.com/Pylons/pyramid_jinja2 to download development or tagged versions.

Visit http://github.com/Pylons/pyramid_jinja2/issues to report bugs.

9.1 Indices and tables

• Glossary

• genindex

• modindex

• search

27

Page 32: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

28 Chapter 9. Reporting Bugs / Development Versions

Page 33: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

Python Module Index

ppyramid_jinja2, 19

29

Page 34: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

pyramid𝑗𝑖𝑛𝑗𝑎2𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛,𝑅𝑒𝑙𝑒𝑎𝑠𝑒2.3.3

30 Python Module Index

Page 35: pyramid 2 - media.readthedocs.org€¦ · CHAPTER 4 Usage Once pyramid_jinja2 has been activated, .jinja2 templates can be used by the Pyramid rendering system. When used as the renderer

Index

Aadd_jinja2_extension() (in module pyramid_jinja2), 19add_jinja2_renderer() (in module pyramid_jinja2), 19add_jinja2_search_path() (in module pyramid_jinja2), 19Asset Specification, 26

CConfigurator, 26

Gget_jinja2_environment() (in module pyramid_jinja2), 20

Iincludeme() (in module pyramid_jinja2), 19

JJinja2, 26Jinja2TemplateRenderer (class in pyramid_jinja2), 20

Mmodel_url_filter() (in module pyramid_jinja2.filters), 15

PPyramid, 26pyramid_jinja2, 26pyramid_jinja2 (module), 19

Rroute_path_filter() (in module pyramid_jinja2.filters), 15route_url_filter() (in module pyramid_jinja2.filters), 15

SSmartAssetSpecLoader (class in pyramid_jinja2), 20static_path_filter() (in module pyramid_jinja2.filters), 15static_url_filter() (in module pyramid_jinja2.filters), 15

TTemplate Inheritance, 26

31