03_load_from_app_directory_and_some_config 

Send to Kindle
home » snippets » python » jinja2 » example » 03_load_from_app_directory_and_some_config



Load a template from the application directory and configure some options.


template.jinja2

##- hello
{#- -#}

Hello {{ name }}!


Output

u'Hello World!'


main.py

# -*- coding: UTF-8 -*-

import jinja2

env = jinja2.Environment(
    # The package name here, "__main__" is present in __name__.
    # For a different module a.b.c, use a.b.c.__name__.
    loader=jinja2.PackageLoader(__name__, ''),

    # Line statements that start a block can optionally end with a ":"
    # They span multiple lines automatically if they open parens, braces or
    # brackets.
    line_statement_prefix="#%",

    # Given this, if you use ##- to start a comment, then the newline before
    # the comment is removed.  However, the newline that ends the line comment
    # isn't remove.  You can stick the empty block {#- -#} on the following
    # line to get rid of it.
    line_comment_prefix="##",

    # The first newline after a block is removed.
    # Default: False.
    trim_blocks=False,

    # A callable used to process the result of a variable expression. Example:
    # Could convert None to ""
    finalize=None,
    )

template = env.get_template('template.jinja2')
print repr(template.render(name="World"))