pythonvisual-studio-codejinja2

Visual Studio Code and Jinja templates


I use VS code since a while with some Extensions. All is perfect expect when I use Flask.

Prettier put all flask code glued together, and intellisence is not working with flask code:

{% extends "layout.html" %} {% block style %} body {color: red; } {% endblock %}
{% block body %} you must provide a name {% endblock %}

What can I do to make it work with flask (trie flask-snippets)?

I run it in virtuel env (run before lauch vscode).

Thanks in advance,


Solution

  • Batteries included solution

    Here is a solution that gives you code highlighting, tag-autocompletion and customizable auto-formatting:

    1. Install Better Jinja or Django (better syntax highlighting within double quotes) plugin
    2. Install djLint plugin
    3. Press CTRL + Shift + P and type open settings json + Enter

    This is my config and it works great for my jinja templates. djLint has more filetype-specific options to offer (see extension-description in VS Code).

    // settings.json
    
    // My jinja-templates use the extension `.jinja2`. To make it work with the "Django" plugin I add this to my settings:
    "files.associations": {
        "*.jinja2": "django-html"
    },
    // Add emmet tag autocomplete for jinja and django templates
    "emmet.includeLanguages": {
        "jinja2": "html",
        "jinja-html": "html",
        "django-html": "html",
    },
    // Set djLint as formatter for html, jinja, jinja-html, django-html
    "[html][jinja][jinja-html][django-html]": {
        "editor.formatOnSave": true,
        "editor.defaultFormatter": "monosans.djlint",
        "editor.detectIndentation": false,
        "editor.linkedEditing": true,
        "editor.tabSize": 2
      },
    // Add specific formatting rules as needed, e.g.:
    "djlint.enableLinting": true,
    "djlint.closeVoidTags": true,
    "djlint.formatAttributeTemplateTags": true,
    "djlint.formatCss": true,
    "djlint.formatJs": true,
    "djlint.lineBreakAfterMultilineTag": false,
    "djlint.maxBlankLines": 2,
    "djlint.maxLineLength": 100,
    "djlint.maxAttributeLength": 100