Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tidy for Jinja2 templates

Is there a tidy-like tool or a tidy configuration, which works fine with Jinja2 templates? The default tidy has problems with Jinja code in attributes and Jinja-loops are formated in an unreadable way. My main requirement is to get the indentation level right. Everything else is nice to have, but not required.

like image 556
Achim Avatar asked Jun 15 '13 13:06

Achim


People also ask

How are templates reused in Jinja2?

To reuse a Jinja template you use the Jinja built-in {% extends %} tag. The {% extends %} tag uses the syntax {% extends <name> %} to reuse the layout of another template. This means that in order to reuse the layout in listing 4-5 defined in a file base.

How does Jinja template work?

Jinja is a fast, expressive, extensible templating engine. Special placeholders in the template allow writing code similar to Python syntax. Then the template is passed data to render the final document.


2 Answers

Standalone

A standalone (Jinja2 lint like) tool can be found here:

https://github.com/ramonsaraiva/jinjaninja

Install:

$ pip install jinjaninja

Usage:

$ jinja-ninja templates/header.html 

Output example:

templates/header.html:8:68 Block closures should also have names `{% endblock %}`

Check jinjaninja@github for more information

Pre-Commit

If as part of your local git setup you use pre-commit, check the

  • pre-commit jinja hooks

Django Templates

If you use Django Templates, I suggest to use django-extensions and make use of: validate_templates

You can use pip to install django-extensions for usage:

 $ pip install django-extensions

Django project settings.py file.:

INSTALLED_APPS = [ ... 
     'django_extensions', 
]

The next time you invoke ./manage.py help you should be able to see all the newly available commands. One is called "validate_templates"

$ python manage.py validate_templates

Visual Code Extension

Visual Code offers two Jinja extensions, the default is "Jinja" but a newer one with more functionality is:

  • Better Jinja
like image 180
Peter Rosemann Avatar answered Sep 22 '22 02:09

Peter Rosemann


While it is not a standalone tool like HTML Tidy, the atom-beautify package for the Atom text editor works fine for me. I use atom-beautify when developing Flask/Jinja2 applications.

like image 43
Nimrod Avatar answered Sep 20 '22 02:09

Nimrod