Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 coding style / best practices

Tags:

jinja2

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.

like image 766
Brian M. Hunt Avatar asked Nov 22 '10 15:11

Brian M. Hunt


People also ask

Is Jinja2 a programming language?

Jinja2 is a modern day templating language for Python developers. It was made after Django's template. It is used to create HTML, XML or other markup formats that are returned to the user via an HTTP request. You can read more here.

What is the difference between Jinja and Jinja2?

In the past it was possible to generate templates from a string with the default environment configuration by using jinja. from_string . Jinja 2 provides a Template class that can be used to do the same, but with optional additional configuration.

What language does Jinja2 use?

Jinja is a web template engine for the Python programming language.


2 Answers

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.

like image 173
Nils von Barth Avatar answered Sep 27 '22 18:09

Nils von Barth


As a set of examples of Jinja2 styles, here's a list of projects using it:

  • Plurk/Solace
  • Coffin
like image 39
2 revs, 2 users 93% Avatar answered Sep 27 '22 19:09

2 revs, 2 users 93%