Primeros pasos

Instalación

djLint está escrito en Python y publicado en PyPI. Con uv, añádelo a tu proyecto como dependencia de desarrollo:

uv add --dev djlint

O instálalo como herramienta independiente:

uv tool install djlint

O con pip:

pip install djlint

O con pipx:

pipx install djlint

O con la fórmula de Homebrew que mantiene la comunidad, en macOS o Linux:

brew install djlint

O con npm. Advertencia: el paquete de npm es solo un envoltorio. Su script de instalación ejecuta pip con el python3 que haya en la ruta de tu sistema e instala la versión de djLint que corresponde a esa publicación del paquete de npm, lo que puede sustituir un djLint más reciente por otro más antiguo. npm no gestionará ni desinstalará el paquete real, así que, si puedes, usa pip.

npm i djlint

Para ejecutar djLint en cada commit, consulta pre-commit.

Uso de la línea de comandos

djLint es una aplicación de línea de comandos. Consulta la página de configuración para una configuración avanzada.

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.

Nota

Si no se encuentra el comando djlint, asegúrate de que Python esté en tu PATH.

Ruta o stdin

djLint funciona con una ruta o con stdin.

Con una ruta:

djlint /path/to/templates --lint

O con un archivo concreto:

djlint /path/to/this.mustache --lint

O con stdin:

echo "<div></div>" | djlint -

stdin también sirve para reformatear código. La salida será solo el código formateado, sin mensajes.

echo "<div></div>" | djlint - --reformat

Salida:

<div></div>

Al leer de stdin, djLint no tiene una ruta real con la que comparar per-file-ignores ni que mostrar en los mensajes, así que usa - por defecto. Pasa --stdin-filename para indicarle a djLint la ruta real del contenido que recibe por la tubería, por ejemplo cuando una integración con un editor le pasa el contenido de un archivo al guardarlo.

echo "<div></div>" | djlint - --stdin-filename templates/index.html

Códigos de salida

Código Significado
0 Todo lo que se le pidió revisar a djLint está limpio, o tu configuración omitió todos los archivos que encontró.
1 djLint encontró errores del linter, o archivos que hay que reformatear. --warn los muestra como advertencias y sale con 0 en su lugar.
2 djLint no revisó lo que le pediste: las rutas no coincidieron con ningún archivo, la línea de comandos o la configuración no eran válidas, o djLint falló.

Solo el código 1 significa que djLint examinó tus plantillas y no le gustó lo que encontró. El código 2 siempre significa que la propia ejecución no cumplió su cometido, así que un pipeline puede tratar ambos casos de forma distinta.

El código 2 es el que detecta una ejecución que no revisó nada en absoluto: una ruta incorrecta, una --extension que ya no coincide o plantillas que se han movido. Sin él, una ejecución así pasa sin avisar.

Los archivos que djLint sí encontró y luego omitió a propósito, mediante exclude, extend_exclude, use_gitignore o require_pragma, no son un error. Esa ejecución sale con 0, porque la configuración hizo exactamente lo que se le indicó. Es también lo que permite que exclude funcione con pre-commit, que pasa los nombres de tus archivos preparados para el commit tanto si quieres que djLint los examine como si no.

Si en tu pipeline es normal que una ruta no tenga plantillas, desactiva el código 2 con allow_empty_input:

djlint /path/to/templates --lint --allow-empty-input