Syntax highlighting for templating languages (Jinja 2, etc)

Jinja 2 is a general-purpose templating engine. It’s a Python library, but it can be used with any file type.

Here is an example of a templated file: https://github.com/jupyter/nbconvert/blob/687651/share/jupyter/nbconvert/templates/classic/base.html.j2. The content inside {% ... %} and {{ ... }} are Jinja 2 templating directives, but the other text is valid HTML.

If you try to edit this file with HTML syntax highlighting in Neovim, you will get syntax errors all over the place.

What’s the best way to deal with this situation in Neovim? Other templating languages also suffer from this problem, but Jinja 2 is the one that I personally have had to deal with.

I am aware of the vim-jinja2 and Vim-Jinja2-Syntax plugins. But those only have specific support for Jinja-templated HTML, whereas I want (ideally) to be able to “inject” Jinja 2 markup into any file type, detectable by the suffix .{filetype}.jinja2 or .{filetype}.j2.

I am interested in solutions that use any combination of Neovim functionality: traditional Vim syntax highlighting, Tree Sitter, LSP semantic tokens, etc. I don’t expect that something exists already in a finished state, so this thread is as much an invitation to discussion as it is a Q&A.

1 Like

Vim has dotted file types for when you want to have to languages, see :h 'ft'. I had the exact same grievance with Jinja, so I made my own plugin: HiPhish / jinja.vim · GitLab (GitHub mirror).

The problem could probably be solved through Tree-sitter as well. Tree-sitter makes it possible to embed languages inside languages, but that will require an existing grammar for each of the languages in the chain.

2 Likes