Add custom tokens in Jinja2 (e.g. %% somevar %%)

flask, jinja2, python, syntax, template-engine

Solution

As far as I know, you can use one set for `block_start_string` and `block_end_string`, as well as one set for `variable_start_string` and `variable_end_string`.

From jinja2/environment.py

`block_start_string`
    The string marking the begin of a block.  Defaults to ``'{%'``.

`block_end_string`
    The string marking the end of a block.  Defaults to ``'%}'``.

`variable_start_string`
    The string marking the begin of a print statement.
    Defaults to ``'{{'``.

`variable_end_string`
    The string marking the end of a print statement.  Defaults to
    ``'}}'``.

You can override these with environment variables. Though, I don't think there is a way to have multiple types recognized. For instance, you can't have `{{` and `<%` both work, but with a little hackery you certainly could.

Problem

I'm making a Flask app for local development (on a Mac) of HTML templates that will eventually be served through ASP.NET. For the purposes of local development, I want a way to replace the contents of .NET-style tokens with some data, meaning that Jinja2 would need to be able to recognize `%% ... %%` tokens in addition to the standard ones: `{{ ... }}`, `<% ... %>`, etc. Everything I've found online pertains to the inclusion of some new functionality within the existing tags (e.g. `{{ my_custom_function | arg1 arg2 }}`) But what about defining a new pattern for tags altogether? Has anyone done this successfully? And will it require modification to the Jinja2 core?

Original source