Today I was starting a new project using minjinja. I've been using Jinja templating for a long time now and it's my preferred templating language so far. However, today in VSCode I had a bizzare issue where everytime I formatted my HTML file it would break the formatting completely.
Before Formatting:
{% extends "base.html.j2" %} {% block title %}Hello{% endblock %} {% block
content %}
<div>
<h1>Hello, World!</h1>
</div>
{% endblock %}
After formatting
{% extends "base.html.j2" %}{% block title %}Hello{% endblock %}{%
block content %}
<div>
<h1>Hello, World!</h1>
</div>
{% endblock %}
This was annoying to say the least. I have two plugins that I thought might have been the issue:
At first I presumed that an update broke them but neither have published new versions in a while. Better Jinja only offers syntax highlighting but I thought there was maybe a chance it was interering with Prettier somehow. As a first test I disabled the Better Jinja extension and the bug persisted. Then I disabled the prettier extension and the issue went away. The result was entirely obvious since Prettier is the actual formatter and with it disabled there was no formatting. Taking a peek at the prettier output I spotted this:
["INFO" - 10:39:06 PM] File Info:
{
"ignored": false,
"inferredParser": "html"
}
Reviewing prettier docs I realized that while prettier has a jinja plugin available (https://github.com/davidodenwald/prettier-plugin-jinja-template) it's not enabled by default. Actually the prettier bundled with the vscode extension doesn't have any plugins installed at all!
To use a plugin prettier needs to be installed separately. Here is a snipper from prettier-vscode docs that explains how using an external Pretter is required to use plugins:
This extension supports Prettier plugins when you are using a locally or globally resolved version of prettier. If you have Prettier and a plugin registered in your package.json, this extension will attempt to register the language and provide automatic code formatting for the built-in and plugin languages.
Solution
To enable prettier to format jinja templates in vscode:
- Prettier must be installed locally/globally using npm
- Prettier jinja extension must be installed
- Prettier must be configured to use the jinja extension
Install prettier
npm install --save-dev --save-exacty prettier prettier-plugin-jinja-template
Enable plugin in .prettierrc
file
{
"plugins": ["prettier-plugin-jinja-template"],
"overrides": [
{
"files": ["*.j2"],
"options": {
"parser": "jinja-template"
}
}
]
}