Flask-Genshi

Flask Integration

  • Templates are looked up in the same places as for Jinja templates, including support for blueprints.
  • Context processors are supported, including the default Flask context of request, session and g etc.
  • Template filters are supported provided they’re not using Jinja specific features.
  • Response objects use the class configured for the Flask application, when rendering responses with a MIME type. This can be used to set an output encoding other than the UTF-8 default.
  • Various signals are emitted in a similar fashion to the template_rendered signal in Flask.

Jinja Integration

Any globals, tests and filters in the jinja_env that are not using Jinja-specific features such as the “evalcontext” are exported to Genshi templates as well, with some modifications:

  • Globals mimicking builtins are not exported – Genshi already exports the native builtins.
  • Tests get “is” prepended to them.
  • Filters are wrapped in Pipe.

As a result Jinja templates translate more easily to Genshi. Take this Jinja example:

<p class="{{ 'even' if 1 is even else 'odd' }}">
  {{ lipsum(html=False) | truncate }}
</p>

With Flask-Genshi you can write this as such:

<p class="${ 'even' if iseven(1) else 'odd' }">
  ${ lipsum(html=False) | truncate }
</p>

Content Types

Flask-Genshi has a concept of “content types” that control how Genshi will parse and serialize a template, and which DOCTYPE to use for HTML and XML documents.

Content types are configured by Internet Media Types, commonly known as MIME types. The type is guessed from the filename extension of the template. It is possible to use glob-style pattern matching in type configurations, with exact matches taking the highest precedence and the catch-all */* taking the lowest. These configurations are included by default:

MIME type Serializer DOCTYPE Dialect
*/* XMLSerializer   MarkupTemplate
text/html HTMLSerializer HTML 5 MarkupTemplate
application/xhtml+xml [1] XMLSerializer XHTML 1.1 MarkupTemplate
text/* TextSerializer   TextTemplate [2]

Notes

[1]

It’s unlikely you want to send XHTML – you don’t get any of the new HTML 5 features and Internet Explorer doesn’t support it at all. With Genshi you also get many of the perceived benefits of XHTML server-side without forcing it on clients.

Sometimes people send XHTML as text/html with HTML compatible markup but this is a hack that causes the browser to parse XHTML according to HTML rules! The default XHTML configuration in Flask-Genshi doesn’t pretend to be HTML and uses the correct MIME type.

[2]Text templates are configured for completeness sake, but Jinja is a much more capable engine for text templating and is always configured in Flask anyway.

API Reference

Primary User API

render(template_name, **context)

Render a template to a response object.

The rendered result is encoded according to the default charset of the response_class and the MIME type of the response is set to that of the rendered template.

This function requires a Flask request context belonging to an application configured with a Genshi instance.

render_template(template_name, **context)

Render a template to a unicode string.

Like render but returns an unencoded unicode string. Primarily useful for purposes other than rendering responses to HTTP requests, such as e-mail templating. Similar to the function of the same name in Flask.

class Genshi(app=None)

Extension object. Holds configuration for the Flask-Genshi extension.

app = Flask(__name__)
genshi = Genshi(app)

You can subscript the instance to get a Template by name, allowing you to apply stream filters with more control.

template = genshi['index.html'] \
         | Transformer('//title').replace('Fabulous Ltd.')
Parameters:app – Short for calling init_app.
init_app(app)

Configure a Flask application for using this extension.

mime_db

A MimeTypes instance used to look up the ContentType configured for a template.

content_types

Maps MIME types to ContentType instances.

get_content_type(mimetype)

Select the ContentType configured for the mimetype.

create_context(base)

Create a Context for rendering templates in, including at least the items in base.

create_loader(app)

Create a template loader for Genshi based on the template folders configured for app and its blueprints.

loader_callback(template)

Called by template loaders when a template is parsed, but not when it is returned from the cache.

The default emits the template_parsed signal.

Additional Utilities

class ContentType(serializer=XMLSerializer(), template_class=MarkupTemplate)

Configuration for how Genshi should parse and render a template.

add_filter(func)

Register func as a stream filter that will be applied when rendering templates of this content type.

generate(template, context, filters)

Generate a stream from the template rendered in the context with the additional filters applied.

load(name, loader)

Load the template named name from the loader.

render(stream)

Render a stream to a unicode string.

class Template(name, filters=None, mimetype=None)

Represents a Genshi template that can be loaded and rendered using the configured ContentType of the current application, and possibly additional filters.

The bitwise or operator can be used to create new instances with additional filters. These do the same:

Template('index.html') | Transformer('//title').replace('Fabulous Ltd.')
Template('index.html', [Transformer('//title').replace('Fabulous Ltd.')])

The mimetype parameter can be used to override which ContentType to render with. For example to render an XHTML template as HTML 5:

return Template('index.xhtml', mimetype='text/html').render_to_response()
Parameters:
  • name – Filename of the template.
  • filters – List of functions to filter the stream with.
  • mimetype – Used to select the ContentType and set on rendered response objects. Guessed from the name parameter if set to None.
render(**context)

Render to a unicode string.

render_to_response(**context)

Render to a response object.

The call interface of this class is an alias of this method.

class Pipe(func, *args, **kwargs)

Wraps a function to be called via the bitwise or operator.

Calling the pipe object as a callable yields a new Pipe with fixed arguments.

This class can be used to mimic Jinja’s “filters”:

>>> length = Pipe(len)
>>> take = Pipe(lambda x, n: x[:n])
>>> [1, 2, 3] | length
3
>>> range(10) | take(5)
[0, 1, 2, 3, 4]

Signals

template_parsed(template)
template_loaded(template)
stream_generated(stream, context, filters)
Fork me on GitHub