Ir al contenido

Primeros pasos

djLint está en PyPI, donde necesita Python 3.11 o posterior, y en npm, que trae su propio Python. En un proyecto de Python, añádelo con uv o pip. En un proyecto de JavaScript, como una app de Angular, un sitio de Eleventy o un tema de Shopify, con npm.

Con uv, añádelo a tu proyecto como dependencia de desarrollo:

Ventana de terminal
uv add --dev djlint

O instálalo como herramienta independiente:

Ventana de terminal
uv tool install djlint

Para ejecutar djLint en tu editor o en cada commit, consulta Integraciones y pre-commit.

Pasa a djLint la carpeta con tus plantillas y el --profile de tu lenguaje de plantillas. El perfil decide qué reglas del linter se aplican y cómo se formatea la sintaxis de las plantillas. Para un proyecto de Django:

Analiza las plantillas (es el modo por defecto, así que puedes omitir --lint):

Ventana de terminal
djlint templates --lint --profile=django

Mira qué cambiaría el formateo. Con --check, djLint muestra un diff y no toca los archivos:

Ventana de terminal
djlint templates --check --profile=django

Formatea los archivos en su sitio:

Ventana de terminal
djlint templates --reformat --profile=django

La opción profile enumera todos los perfiles. Cada lenguaje de plantillas tiene además su propia página, por ejemplo Django, Jinja o Handlebars, donde se explica cómo fijar el perfil en un archivo de configuración para no tener que pasarlo cada vez.

Si añadiste djLint al proyecto con uv add --dev, está en el entorno del proyecto: antepón uv run a los comandos, por ejemplo uv run djlint templates --lint --profile=django. Con npm i -D, antepón npx en su lugar, por ejemplo npx djlint templates --lint --profile=django.

djLint funciona con una ruta o con stdin.

Con una ruta:

Ventana de terminal
djlint /path/to/templates --lint

O con un archivo concreto:

Ventana de terminal
djlint /path/to/this.mustache --lint

O con stdin:

Ventana de terminal
echo "<div></div>" | djlint -

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

Ventana de terminal
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.

Ventana de terminal
echo "<div></div>" | djlint - --stdin-filename templates/index.html
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, no se pudo leer un archivo (no es UTF-8, o no hay permiso), 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ó, así que un pipeline puede distinguir una comprobación que falla de una ejecución que no revisó nada, como una con una ruta incorrecta o una --extension que ya no coincide.

Los archivos que djLint encontró y luego omitió a propósito, mediante exclude, extend_exclude, use_gitignore o require_pragma, no son un error, y eso es lo que permite que exclude funcione con pre-commit. Si en tu pipeline es normal que una ruta no tenga plantillas, desactiva el código 2 con allow_empty_input:

Ventana de terminal
djlint /path/to/templates --lint --allow-empty-input
Usage: djlint [OPTIONS] SRC ...
djLint · HTML template linter and formatter.
Modes:
--lint Lint the files. This is the default when
neither --reformat nor --check is given.
--reformat Format the files in place.
--check Show what formatting would change, without
changing the files.
--lsp Run as a language server over stdio, for
editors.
Files:
-e, --extension EXT Extension of the files to look for in folders.
[default: html]
--exclude PATHS Regexes of the paths to skip, comma-separated,
in place of the default list.
--extend-exclude PATHS Regexes of the paths to skip on top of the
exclude list, comma-separated.
--use-gitignore Also skip the paths that the .gitignore in the
project root lists.
--require-pragma Only format or lint files whose first line is
a djlint:on comment.
--stdin-filename PATH Path that stands for stdin in messages,
excludes and per-file ignores. [default: -]
--allow-empty-input Exit with 0 instead of 2 when the given paths
match no files.
Configuration:
--profile NAME Template language: html, django, jinja,
nunjucks, handlebars, liquid, golang, angular,
tera, askama, mako or all. It decides which
linter rules run and how template syntax is
formatted. Without one, formatting follows all
and the linter runs the rules of html.
--configuration FILE Global config file: a pyproject.toml,
djlint.toml or .djlintrc. The project's own
config file wins where both set an option.
--prefer-configuration Let the --configuration file win over the
project's own config file.
Linter:
-i, --ignore CODES Linter codes to skip, comma-separated, for
example H014,H017.
--include CODES Linter codes to turn on, comma-separated, for
example H017. Works for rules that are off by
default and for rules the profile leaves out.
--per-file-ignores <PATTERN CODES>...
Skip linter codes in the files whose path
matches a regex. Can be repeated.
--rules FILE Custom linter rules, in the .djlint_rules.yaml
format.
Output:
--quiet Do not print diffs, the progress bar or the
summary.
--warn Exit with 0 instead of 1 when there are lint
errors or files to reformat.
--statistics After linting, print how many times each code
was found.
--linter-output-format FORMAT Layout of each lint message, from {filename},
{line}, {end}, {code}, {message} and {match}.
[default: {code} {line} {message} {match}]
--github-output / --no-github-output
Print results as GitHub Actions annotations.
On by default inside GitHub Actions.
--sarif Print findings as a SARIF 2.1.0 JSON document,
for GitHub code scanning and other tools.
Layout:
--indent N Spaces per indent level. [default: 4, or
indent_size from .editorconfig]
--max-line-length N Join tags onto one line only when the line
fits within this length. [default: 120, or
max_line_length from .editorconfig]
--max-attribute-length N Spread a tag's attributes over lines once they
are longer than this. [default: 70]
--single-attribute-per-line When an opening tag wraps, put each attribute
on its own line.
--line-break-after-multiline-tag
When a tag's attributes are spread over lines,
start its content on a new line.
--no-indent-inner-html Do not indent <head> and <body> inside <html>.
--keep-br-inline Keep <br> on the line of the text it breaks.
--custom-blocks TAGS Names of the custom template blocks to indent,
comma-separated, for example toc.
--custom-html TAGS Names of the custom HTML tags to indent,
comma-separated, for example mjml.
--ignore-blocks TAGS Template blocks that do not indent their
contents, comma-separated.
--blank-line-after-tag TAGS Template tags to follow with a blank line,
comma-separated, for example load,extends.
--blank-line-before-tag TAGS Template tags to precede with a blank line,
comma-separated, for example load,extends.
--max-blank-lines N Keep at most this many blank lines in a row.
Has no effect with --preserve-blank-lines.
[default: 0]
--preserve-blank-lines Keep blank lines where possible.
--preserve-leading-space Keep the leading spaces of text lines where
possible.
--no-line-after-yaml Do not add a blank line after YAML front
matter.
Rewrites:
--close-void-tags Close void tags with a slash, so <img> becomes
<img />.
--ignore-case Do not fix the case of known HTML tags.
--sort-attributes Sort attributes by name, with id first and
class second.
--sort-load-tags Sort the libraries in {% load %} tags and drop
repeated ones.
--name-endblocks Name the block in its {% endblock %} when the
block spans lines.
--quote-style [double|single] Quotes for strings inside template tags.
[default: double]
--no-entity-formatting Do not rewrite entity references such as
&copy; as the characters they name.
--no-function-formatting Do not format the arguments of function calls
inside {{ }}.
--no-set-formatting Do not format the contents of {% set %} tags.
--preserve-class-newlines Keep the line breaks in class attributes
written across lines.
--format-attribute-template-tags
Format template syntax inside tag attributes.
CSS and JavaScript:
--format-css Also format the contents of <style> tags, with
css-beautify.
--indent-css N Indent width inside <style> tags, for
--format-css. [default: 4]
--format-js Also format JavaScript and JSON in <script>
tags, with js-beautify.
--indent-js N Indent width inside <script> tags, for
--format-js. [default: 4]
--format-attribute-js-json Also format JavaScript and JSON in attributes
such as onclick and x-data.
--format-attribute-js-json-pattern REGEX
Regex for the names of the attributes to
format as JavaScript or JSON. [default: on*
event handlers and Alpine, Vue, Angular and
Aurelia bindings]
--format-attribute-js-json-min-props N
Format an object only when it has at least
this many properties. [default: 2]
Other:
--version Show the version and exit.
-h, --help Show this message and exit.