pythonflaskjinja2

Create second Jinja environment in Flask app


I want to create a second Jinja environment to generate LaTeX document. This snippet uses Flask.create_jinja_environment, but I want to use a custom loader: FileSystemLoader('/path/to/latex/templates'). How can I create an env like the snippet but use my custom loader?

LATEX_SUBS = (
    (re.compile(r'\\'), r'\\textbackslash'),
    (re.compile(r'([{}_#%&$])'), r'\\\1'),
    (re.compile(r'~'), r'\~{}'),
    (re.compile(r'\^'), r'\^{}'),
    (re.compile(r'"'), r"''"),
    (re.compile(r'\.\.\.+'), r'\\ldots'),
)

def escape_tex(value):
    newval = value
    for pattern, replacement in LATEX_SUBS:
        newval = pattern.sub(replacement, newval)
    return newval

texenv = app.create_jinja_environment()
texenv.block_start_string = '((*'
texenv.block_end_string = '*))'
texenv.variable_start_string = '((('
texenv.variable_end_string = ')))'
texenv.comment_start_string = '((='
texenv.comment_end_string = '=))'
texenv.filters['escape_tex'] = escape_tex

Solution

  • That snippet uses create_jinja_environment so that the templates are loaded from the same place the app templates are. This is most likely what you want, just create a directory in your app's templates folder with the LaTeX templates.

    You can still use create_jinja_environment and just replace the loader just like the snippet replaces other attributes on the env.

    texenv = app.create_jinja_environment()
    texenv.loader = FileSystemLoader('/path/to/latex/templates')