Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a formatter in vscode for HTML and Jinja?

I'm using vs code and it has auto formating which is great, however, when I write HTML files and use Jinja or DTL, it formats terribly. How do I either disable formatting for this or change it?

I've installed an extension for formatting called Prettier.

This is what I get:

{{ block.super }}

{% endblock styling%} {% block title %} Game {{ game.firs_player }} vs.
{{ game.second_player }} {% endblock title %} {% block content %} This is a
detial page for game {{ game.id }}
{% endblock content %}

This is what I want:

{% load staticfiles %} 

{% block styling%}
    {{ block.super }}
{% endblock styling%} 

{% block title %} 
    Game {{ game.firs_player }} vs.{{ game.second_player }} 
{% endblock title %} 

{% block content %} 
    This is a detial page for game {{ game.id }}
{% endblock content %}```
like image 594
Duje Avatar asked May 10 '19 13:05

Duje


People also ask

How do I beautify HTML code in VSCode?

To improve the formatting of your HTML source code, you can use the Format Document command Ctrl+Shift+I to format the entire file or Format Selection Ctrl+K Ctrl+F to just format the selected text. The HTML formatter is based on js-beautify.

How do I use code formatter in VSCode?

The code formatting is available in Visual Studio Code (VSCode) through the following shortcuts or key combinations: On Windows Shift + Alt + F. On macOS Shift + Option + F. On Linux Ctrl + Shift + I.

How do I set the default formatter in my VS code settings?

Now, highlight your code and right-click. Select Format Document. Once you click on Format Document, a dialog box will tell you to configure your code formatter. This is to set your default code formatter.

Can I use Jinja in HTML?

Jinja can generate any text-based format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn't need to have a specific extension: . html , . xml , or any other extension is just fine.


1 Answers

You could use beautify. It isn't perfect, but it gets the job done.

After you installed it, add this to your settings.json file:

"beautify.language": {
        "js": {
            "type": [
                "javascript"
            ],
            "filename": [
                ".jshintrc",
                ".jsbeautifyrc"
            ]
            // "ext": ["js", "json"]
            // ^^ to set extensions to be beautified using the javascript beautifier
        },
        "css": [
            "css",
            "scss"
        ],
        "html": [
            "htm",
            "html",
            "django-html"
        ]
        // ^^ providing just an array sets the VS Code file type
    },

Now, it should work with Django template files.

like image 80
Daniel Diaz Avatar answered Oct 18 '22 23:10

Daniel Diaz