One annoying missing feature in most JetBrains IDEs is the lack of builtin support for Jinja2 templates, used notably as the Ansible template engine.
One paid solution exists, the OrchidE plugin, but there is a free workaround. Can you guess which one ?
One template engine which originally got a lot of inspiration from Jinja is the PHP Twig engine made popular by Symfony.
Even today, in spite of the divergent evolutions of Jinja 3 and Twig 3, it is close enough in basic syntax for the Twig plugin to be used to edit Ansible Jinja templates. And the JetBrains Twig plugin has a very useful feature in the form of "sub-templates". That is, providing syntax support for both the template engine itself (the braces content) and the template destination (YAML, INI, Apache Config, etc).
This relies on having template files named (file).(target type).twig
: on such files the Twig plugin applies Twig (Jinja) syntax to the braces content and target type syntax to the rest of the file. For example, we could create a myvhost.apacheconf.twig
file and have it be edited as a "Jinja" template targeting an Apache config file, with the following steps:
- Go to Preferences / Editor / File Types, add
*.apacheconf
to the Apache config type; validate. - Create your Apache vhost template as
my_vhost.j2
. - Symlink it to
my_vhost.apacheconf.twig
. - Enjoy !
If you don't mind going for a more unusual, but even simpler approach, you can even forego the *.j2
extension altogether, and name your templates that way, also when referencing them as template.src
arguments: no symlinks, no problems.
Ansible does not actually care about the template extensions to try to infer an engine, so a *.twig
works just as well as a *.j2
.
Just don't forget to document why your templates are named that way in your project README file: other devs could be surprised to see that unusual extension.
Twig extension is not necessary
Thanks for this suggestion. I was able to figure out the whole solution based on your input above. Actually, you don't need to do all this complicated symlinking or .twig extension mess. You can simply configure JetBrains to use twig file type for j2 extension files. Go to
File > Preferences > Editor > File Types
. Then UnderRecognized File Types
selectTwig
and add*.j2
in File name patterns.Thanks for the suggestion …