Начало работы
Установка
Заголовок раздела «Установка»djLint есть в PyPI, где ему нужен Python 3.11 или новее, и в npm, где он поставляется со своим Python. В проект на Python добавляйте его через uv или pip, в проект на JavaScript, например приложение на Angular, сайт на Eleventy или тему Shopify, через npm.
С uv добавьте его в проект как зависимость для разработки:
uv add --dev djlintИли установите его как отдельный инструмент:
uv tool install djlintpip install djlintnpm-пакет поставляется со своим Python, так что ему нужен только Node.js 16.9 или новее. Есть сборки для Linux на x64, Arm64, ppc64le, s390x и riscv64, macOS на x64 и Arm64 и Windows на x64, x86 и Arm64. На Linux с musl, например Alpine, он работает на x64 и Arm64. Добавьте его в проект как зависимость для разработки:
npm i -D djlintИли установите его глобально:
npm i -g djlintЧерез pipx:
pipx install djlintЧерез формулу Homebrew, которую поддерживает сообщество, на macOS или Linux:
brew install djlintЧтобы запускать djLint в редакторе или при каждом коммите, см. разделы Интеграции и pre-commit.
Первый запуск
Заголовок раздела «Первый запуск»Передайте djLint папку с шаблонами и укажите в --profile язык шаблонов. От профиля зависит, какие правила линтера сработают и как будет отформатирован синтаксис шаблонов. Для проекта на Django:
Проверьте шаблоны (это режим по умолчанию, так что --lint можно не писать):
djlint templates --lint --profile=djangoПосмотрите, что изменит форматирование. С --check djLint выводит diff и не трогает файлы:
djlint templates --check --profile=djangoОтформатируйте файлы на месте:
djlint templates --reformat --profile=djangoВсе профили перечислены в описании опции profile. У каждого языка шаблонов есть и своя страница, например Django, Jinja или Handlebars. Там же показано, как задать профиль в файле конфигурации, чтобы не передавать его каждый раз.
Если djLint добавлен в проект через uv add --dev, он лежит в окружении проекта: запускайте команды через uv run, например uv run djlint templates --lint --profile=django. После npm i -D запускайте их через npx, например npx djlint templates --lint --profile=django.
Путь или stdin
Заголовок раздела «Путь или stdin»djLint принимает на вход путь или стандартный ввод (stdin).
Запуск с путём:
djlint /path/to/templates --lintИли с конкретным файлом:
djlint /path/to/this.mustache --lintИли через stdin:
echo "<div></div>" | djlint -Через stdin можно и переформатировать код. Тогда выводится только отформатированный код, без сообщений.
echo "<div></div>" | djlint - --reformatВывод:
<div></div>При чтении из stdin у djLint нет настоящего пути, с которым можно сопоставить per-file-ignores и который можно показать в сообщениях, поэтому по умолчанию используется -. Передайте --stdin-filename, чтобы сообщить djLint настоящий путь переданного содержимого, например когда интеграция с редактором передаёт содержимое файла при сохранении.
echo "<div></div>" | djlint - --stdin-filename templates/index.htmlКоды завершения
Заголовок раздела «Коды завершения»| Код | Значение |
|---|---|
0 |
Всё, что djLint должен был проверить, в порядке, или каждый найденный файл пропущен согласно вашей конфигурации. |
1 |
djLint нашёл ошибки линтера или файлы, которые нужно переформатировать. С --warn они выводятся как предупреждения, а код завершения вместо этого будет 0. |
2 |
djLint не проверил то, что вы просили: пути не совпали ни с одним файлом, файл не удалось прочитать (не UTF-8 или нет прав), командная строка или конфигурация некорректны либо в djLint произошёл сбой. |
Только код 1 означает, что djLint просмотрел ваши шаблоны и ему не понравилось то, что он нашёл, поэтому конвейер может отличить непройденную проверку от запуска, который ничего не проверил, например с неверным путём или с --extension, который больше ничему не соответствует.
Файлы, которые djLint нашёл, а затем намеренно пропустил из-за exclude, extend_exclude, use_gitignore или require_pragma, ошибкой не считаются, и благодаря этому exclude работает в pre-commit. Если для вашего конвейера нормально, что по пути нет шаблонов, отключите код 2 параметром allow_empty_input:
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 © 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.