Pyramid Jinja2

2.10.1 · active · verified Sat Apr 11

Pyramid Jinja2 is a set of bindings that integrate the Jinja2 templating system with the Pyramid web framework. Currently at version 2.10.1, it is actively maintained by the Pylons Project, offering robust template rendering capabilities for Pyramid applications.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic Pyramid application using `pyramid_jinja2` to render templates. It sets up two routes with corresponding views, each rendering a different Jinja2 template. The `config.include('pyramid_jinja2')` line is crucial for activating the Jinja2 renderer, and `jinja2.directories` is configured to locate templates.

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.view import view_config

# Assuming a 'templates' directory exists with 'home.jinja2' in the same package
# e.g., myapp/templates/home.jinja2

@view_config(route_name='home', renderer='home.jinja2')
def home_view(request):
    return {'project': 'pyramid_jinja2 example', 'name': request.matchdict.get('name', 'World')}

@view_config(route_name='hello', renderer='templates/hello.jinja2')
def hello_view(request):
    return {'name': request.matchdict.get('name', 'Guest')}

if __name__ == '__main__':
    with Configurator() as config:
        config.include('pyramid_jinja2')
        config.add_settings({'jinja2.directories': 'myapp:templates'}) # Or pass to Configurator(settings=...)
        config.add_route('home', '/')
        config.add_route('hello', '/hello/{name}')
        config.scan('.') # Scans for @view_config decorators
        app = config.make_wsgi_app()

    server = make_server('0.0.0.0', 6543, app)
    print('Serving Pyramid Jinja2 app on http://0.0.0.0:6543')
    print("Try: http://localhost:6543/ and http://localhost:6543/hello/Alice")
    server.serve_forever()

# Example template (myapp/templates/home.jinja2):
# <h1>Welcome to {{ project }}!</h1>
# <p>Hello, {{ name }}!</p>

# Example template (myapp/templates/hello.jinja2):
# <h1>Greetings!</h1>
# <p>Hello, {{ name }} from a different template!</p>

view raw JSON →