Search code examples
jinja2

Jinja2 coding style / best practices


Do you have a best-practices and coding style when developing with Jinja2?

Personally, I like the style in Plurk/Solace, but I'd like to know what other styles and practices people use when writing Jinja2.


Solution

  • Chromium has a detailed Jinja style guide — I'm the original author, based on personal use, feedback from colleagues, and reviewing others' code.

    Beyond Jinja-specific guidelines — mostly "keep it simple, since it's an unfamiliar DSL" and many tips — the subtlest question is how to structure the Python code, and the Python/Jinja interaction. Our main conclusions:

    • Logic in Python (over one line should go in Python; keep Jinja simple).
    • One-way flow: Python → Jinja. Do not call Python from Jinja (other than custom filters), to avoid complexity.
    • Define each context in one dictionary display. This is your Python/Jinja interface, and is much easier to understand than building a dictionary piecemeal.

    Jinja has powerful features, but most uses are pretty simple templates written by people who rarely use Jinja, so the goal is to put the text chunks and basic string processing in Jinja, but keep the complex logic in Python, which is better-suited and more familiar.