Primeiros passos
Instalação
O djLint é feito em Python e publicado no PyPI. Com o uv, adicione-o ao seu projeto como dependência de desenvolvimento:
uv add --dev djlint
Ou instale-o como uma ferramenta independente:
uv tool install djlint
Ou com o pip:
pip install djlint
Ou com o pipx:
pipx install djlint
Ou com a fórmula do Homebrew mantida pela comunidade, no macOS ou no Linux:
brew install djlint
Ou com o npm. Atenção: o pacote npm é apenas um wrapper. O script de instalação dele executa o pip com o python3 que estiver no PATH do seu sistema e instala a versão do djLint correspondente àquela release do npm, o que pode substituir um djLint mais novo por um mais antigo. O npm não vai gerenciar nem desinstalar o pacote de fato, então prefira o pip sempre que puder.
npm i djlint
Para executar o djLint a cada commit, consulte pre-commit.
Uso da CLI
O djLint é um aplicativo de linha de comando. Consulte a página de configuração para a configuração avançada.
Usage: djlint [OPTIONS] SRC ...
djLint · HTML template linter and formatter.
Options:
--version Show the version and exit.
--lsp Run as a language server over stdio, for
editors.
-e, --extension TEXT File extension to check [default: html]
-i, --ignore TEXT Codes to ignore. ex: "H014,H017"
--reformat Reformat the file(s).
--check Check formatting on the file(s).
--stdin-filename TEXT Filename to use for per-file-ignores and
messages when reading from stdin. [default: -]
--indent INTEGER Indent spacing. [default: 4]
--quiet Do not print diff when reformatting.
--profile TEXT Enable defaults by template language. ops:
django, jinja, nunjucks, handlebars, liquid,
golang, angular, tera, askama, html [default:
html]
--require-pragma Only format or lint files that starts with a
comment with the text 'djlint:on'
--lint Lint for common issues. [default option]
--use-gitignore Use .gitignore file to extend excludes.
--allow-empty-input Exit with 0 instead of 2 when the given paths
match no files.
--warn Return errors as warnings.
--preserve-leading-space Attempt to preserve leading space on text.
--preserve-blank-lines Attempt to preserve blank lines.
--preserve-class-newlines Preserve line breaks inside multiline class
attributes.
--format-css Also format contents of <style> tags.
--format-js Also format contents of <script> tags.
--format-attribute-js-json Also format JavaScript/JSON inside HTML
attributes.
--format-attribute-js-json-pattern TEXT
Regex pattern to match JavaScript attributes.
--format-attribute-js-json-min-props INTEGER
Minimum number of properties to treat
attribute content as JS/JSON.
--configuration FILE Path to global configuration file in
djlint.toml, .djlint.toml, or .djlintrc format
--prefer-configuration Let --configuration override the project's own
config file, rather than the other way round.
--rules FILE Path to custom rules file in
.djlint_rules.yaml format
--statistics Count the number of occurrences of each
error/warning code.
--include TEXT Codes to include. ex: "H014,H017"
--ignore-case Do not fix case on known html tags.
--ignore-blocks TEXT Comma list of template blocks to not indent.
--blank-line-after-tag TEXT Add an additional blank line after {% <tag>
... %} tag groups.
--blank-line-before-tag TEXT Add an additional blank line before {% <tag>
... %} tag groups.
--line-break-after-multiline-tag
Do not condense the content of multi-line tags
into the line of the last attribute.
--custom-blocks TEXT Indent custom template blocks. For example {%
toc %}...{% endtoc %}
--custom-html TEXT Indent custom HTML tags. For example <mjml>
--exclude TEXT Override the default exclude paths.
--extend-exclude TEXT Add additional paths to the default exclude.
--linter-output-format TEXT Customize order of linter output message.
--max-line-length INTEGER Max line length. [default: 120]
--max-attribute-length INTEGER Max attribute length. [default: 70]
--format-attribute-template-tags
Attempt to format template syntax inside of
tag attributes.
--single-attribute-per-line When an opening tag wraps, put each attribute
on its own line.
--per-file-ignores <TEXT TEXT>...
Ignore linter rules on a per-file basis.
--indent-css INTEGER Set CSS indent level.
--indent-js INTEGER Set JS indent level.
--close-void-tags Add closing mark on known void tags. Ex: <img>
becomes <img />
--no-line-after-yaml Do not add a blank line after yaml front
matter.
--name-endblocks Name the endblock of a block written across
lines.
--sort-attributes Sort attributes by name, with id first and
class second.
--sort-load-tags Sort the libraries in {% load %} tags.
--no-indent-inner-html Do not indent <head> and <body> below <html>.
--no-function-formatting Do not attempt to format function contents.
--no-set-formatting Do not attempt to format set contents.
--keep-br-inline Keep <br> on the line of the text it breaks.
--no-entity-formatting Do not rewrite entity references as
characters.
--quote-style [double|single] Quotes to use for strings inside template
tags. [default: double]
--max-blank-lines INTEGER Consolidate blank lines down to x lines.
[default: 0]
--github-output / --no-github-output
Output GitHub-compatible formatting.
--sarif Output findings as SARIF 2.1.0 json, for
GitHub code scanning and other tools.
-h, --help Show this message and exit.
Usando caminho ou stdin
O djLint funciona com um caminho ou com o stdin.
Executando com um caminho -
djlint /path/to/templates --lint
Ou com um arquivo específico -
djlint /path/to/this.mustache --lint
Ou com o stdin -
echo "<div></div>" | djlint -
O stdin também pode ser usado para reformatar código. A saída será apenas o código formatado, sem mensagens.
echo "<div></div>" | djlint - --reformat
Saída -
<div></div>
Ao ler do stdin, o djLint não tem um caminho real para comparar com per-file-ignores nem para mostrar nas mensagens, então usa - por padrão. Passe --stdin-filename para informar ao djLint o caminho real do conteúdo recebido pelo pipe, por exemplo quando uma integração com editor envia o conteúdo de um arquivo pelo pipe ao salvar.
echo "<div></div>" | djlint - --stdin-filename templates/index.html
Códigos de saída
| Código | Significado |
|---|---|
0 |
Tudo o que você pediu para o djLint verificar está limpo, ou todos os arquivos encontrados foram ignorados pela sua configuração. |
1 |
O djLint encontrou erros de lint ou arquivos que precisam ser reformatados. --warn relata esses casos como avisos e, em vez disso, sai com 0. |
2 |
O djLint não verificou o que você pediu: os caminhos não corresponderam a nenhum arquivo, a linha de comando ou a configuração era inválida, ou o djLint falhou. |
Somente o código 1 significa que o djLint analisou seus templates e não gostou do que encontrou. O código 2 sempre significa que a própria execução não cumpriu seu papel, então um pipeline pode tratar os dois de forma diferente.
O código 2 é o que detecta uma execução que não verificou absolutamente nada: um caminho errado, uma --extension que não corresponde mais a nada, ou templates que foram movidos. Sem ele, uma execução assim passa silenciosamente.
Arquivos que o djLint encontrou e depois ignorou de propósito, por meio de exclude, extend_exclude, use_gitignore ou require_pragma, não são um erro. Essa execução sai com 0, porque a configuração fez exatamente o que lhe foi pedido. É também isso que permite que exclude funcione com o pre-commit, que passa os nomes dos seus arquivos preparados para commit, quer você queira ou não que o djLint os analise.
Se um caminho que legitimamente não tem templates for normal no seu pipeline, desative o código 2 com allow_empty_input:
djlint /path/to/templates --lint --allow-empty-input