diff --git a/docs/src/_data/i18n/index.js b/docs/src/_data/i18n/index.js index 8f4ff27..ce1edf2 100644 --- a/docs/src/_data/i18n/index.js +++ b/docs/src/_data/i18n/index.js @@ -129,5 +129,10 @@ module.exports = { 'en-US': 'Edit this page', ru: 'Редактировать эту страницу', fr: 'Modifier cette page', + }, + ignoring_code: { + 'en-US': 'Ignoring Code', + ru: 'Игнорирование Контент', + fr: 'Ignorer le Contenu', } }; diff --git a/docs/src/_includes/docs_layout.njk b/docs/src/_includes/docs_layout.njk index d2f8b7a..ab51b40 100644 --- a/docs/src/_includes/docs_layout.njk +++ b/docs/src/_includes/docs_layout.njk @@ -15,6 +15,7 @@ layout: layout.njk {{ "getting_started" | i18n }}
  • {{ "formatter" | i18n }}
  • {{ "linter" | i18n }}
  • +
  • {{ "ignoring_code" | i18n }}
  • {{ "configuration" | i18n }}
  • {{ "integrations" | i18n }}
  • {{ "best_practices" | i18n }}
  • diff --git a/docs/src/docs/formatter.md b/docs/src/docs/formatter.md index 58cad48..bf8417d 100644 --- a/docs/src/docs/formatter.md +++ b/docs/src/docs/formatter.md @@ -38,46 +38,6 @@ djlint . --reformat "djLint is not an html parser or syntax validator." %} -## Ignoring Code - -Code can be ignored by wrapping it in `djlint` tags: - -{% raw %} - -For plain old html - - -```html - - -``` - -or as a comment - - -```html -{# djlint:off #} {# djlint:on #} -``` - -or as a long comment - - -```html -{% comment %} djlint:off {% endcomment %} - {% comment %} djlint:on {% endcomment %} -``` - -or as a javascript style comment - - -```html -{{ /* djlint:off */ }} {{ /* djlint:on */ }} -``` - -or as a golang style comment - - -```html -{{!-- djlint:off --}} {{!-- djlint:on --}} -``` - -{% endraw %} - ## Here's an example! ### Before diff --git a/docs/src/docs/ignoring-code.md b/docs/src/docs/ignoring-code.md new file mode 100644 index 0000000..a3246c3 --- /dev/null +++ b/docs/src/docs/ignoring-code.md @@ -0,0 +1,74 @@ +--- +description: How to prevent djLint from formatting a block of code. How ignore djLint rules inline. +title: Ignoring Code +keywords: template linter, template formatter, djLint, HTML, templates, formatter, linter, formatter usage, ignore code, ignore rules +date: Last Modified +--- + +# Ignoring Code + +Code can be ignored by wrapping it in `djlint` tags: + +{% raw %} + +For plain old html - + +```html + + +``` + +or as a comment - + +```html +{# djlint:off #} {# djlint:on #} +``` + +or as a long comment - + +```html +{% comment %} djlint:off {% endcomment %} + {% comment %} djlint:on {% endcomment %} +``` + +or as a javascript style comment - + +```html +{{ /* djlint:off */ }} {{ /* djlint:on */ }} +``` + +or as a golang style comment - + +```html +{{!-- djlint:off --}} {{!-- djlint:on --}} +``` + +{% endraw %} + +## Ignoring Rules + +Specific linter rules can also be ignored by adding the rule name into the ignored block opening tag. + +{% raw %} +```html +{# djlint:off H025,H026 #} +

    +{# djlint:on #} + + +

    + + +{% comment %} djlint:off H025 {% endcomment %} +

    +{% comment %} djlint:on {% endcomment %} + +{{!-- djlint:off H025 --}} +

    +{{!-- djlint:on --}} + +{{ /* djlint:off H025 */ }} +

    +{{ /* djlint:on */ }} +``` +{% endraw %} diff --git a/docs/src/fr/docs/formatter.md b/docs/src/fr/docs/formatter.md index 8a4dc35..aad6225 100644 --- a/docs/src/fr/docs/formatter.md +++ b/docs/src/fr/docs/formatter.md @@ -38,45 +38,6 @@ djlint . --reformat "djLint n'est pas un analyseur html ou un validateur de syntaxe." %} -## Ignorer le code - -Le code peut être ignoré en l'entourant de balises `djlint` : - -{% raw %} - -Pour le simple html - - -```html - - -``` - -ou comme un long commentaire - - -```html -{# djlint:off #} {# djlint:on #} -``` - -ou comme un long commentaire - - -```html -{% comment %} djlint:off {% endcomment %} - {% comment %} djlint:on {% endcomment %} -``` - -ou comme un commentaire de style javascript - - -```html -{{ /* djlint:off */ }} {{ /* djlint:on */ }} -``` - -ou comme un commentaire de style golang - - -```html -{{!-- djlint:off --}} {{!-- djlint:on --}} -``` - -{% endraw %} ## Voici un exemple ! diff --git a/docs/src/fr/docs/ignoring-code.md b/docs/src/fr/docs/ignoring-code.md new file mode 100644 index 0000000..bf28ec7 --- /dev/null +++ b/docs/src/fr/docs/ignoring-code.md @@ -0,0 +1,74 @@ +--- +description: Comment empêcher djLint de formater un bloc de code. Comment ignorer les règles de djLint en ligne. +title: Ignorer le code +keywords: template linter, template formatter, djLint, HTML, templates, formatter, linter, formatter usage, ignorer le code, ignorer les règles +date: Last Modified +--- + +## Ignorer le code + +Le code peut être ignoré en l'entourant de balises `djlint` : + +{% raw %} + +Pour le simple html - + +```html + + +``` + +ou comme un long commentaire - + +```html +{# djlint:off #} {# djlint:on #} +``` + +ou comme un long commentaire - + +```html +{% comment %} djlint:off {% endcomment %} + {% comment %} djlint:on {% endcomment %} +``` + +ou comme un commentaire de style javascript - + +```html +{{ /* djlint:off */ }} {{ /* djlint:on */ }} +``` + +ou comme un commentaire de style golang - + +```html +{{!-- djlint:off --}} {{!-- djlint:on --}} +``` + +{% endraw %} + +## Ignorer les règles + +Des règles spécifiques de linter peuvent également être ignorées en ajoutant le nom de la règle dans la balise d'ouverture du bloc ignoré. + +{% raw %} +```html +{# djlint:off H025,H026 #} +

    +{# djlint:on #} + + +

    + + +{% comment %} djlint:off H025 {% endcomment %} +

    +{% comment %} djlint:on {% endcomment %} + +{{!-- djlint:off H025 --}} +

    +{{!-- djlint:on --}} + +{{ /* djlint:off H025 */ }} +

    +{{ /* djlint:on */ }} +``` +{% endraw %} diff --git a/docs/src/ru/docs/formatter.md b/docs/src/ru/docs/formatter.md index 2c71499..cd05a92 100644 --- a/docs/src/ru/docs/formatter.md +++ b/docs/src/ru/docs/formatter.md @@ -38,46 +38,6 @@ djlint . --reformat "djLint не является парсером html или синтаксическим валидатором." %} -## Игнорирование кодекса - -Код можно игнорировать, обернув его в теги `djlint`: - -{% raw %} - -Для простого старого html - - -```html - -<плохой html, который следует игнорировать> -``` - -или как комментарий - - -```html -{# djlint:off #} <плохой html, который следует игнорировать> {# djlint:on #} -``` - -или в виде длинного комментария - -```html -{% comment %} djlint:off {% endcomment %} -<плохой html, который следует игнорировать> {% comment %} djlint:on {% endcomment %} -``` - -или как комментарий в стиле javascript - - -```html -{{ /* djlint:off */ }} <плохой html, который следует игнорировать> {{ /* djlint:on */ }} -``` - -или как комментарий в стиле golang - - -```html -{{!-- djlint:off --}} <плохой html, который следует игнорировать> {{!-- djlint:on --}} -``` - -{% endraw %} - ## Вот пример! ### До diff --git a/docs/src/ru/docs/ignoring-code.md b/docs/src/ru/docs/ignoring-code.md new file mode 100644 index 0000000..ba05d59 --- /dev/null +++ b/docs/src/ru/docs/ignoring-code.md @@ -0,0 +1,74 @@ +--- +description: Как запретить djLint форматировать блок кода. Как игнорировать правила djLint в строке. +title: Игнорирование кодекса +keywords: облицовка шаблонов, форматер шаблонов, djLint, HTML, шаблоны, форматер, линтер, использование, Использование форматера +date: Last Modified +--- + +## Игнорирование кодекса + +Код можно игнорировать, обернув его в теги `djlint`: + +{% raw %} + +Для простого старого html - + +```html + +<плохой html, который следует игнорировать> +``` + +или как комментарий - + +```html +{# djlint:off #} <плохой html, который следует игнорировать> {# djlint:on #} +``` + +или в виде длинного комментария + +```html +{% comment %} djlint:off {% endcomment %} +<плохой html, который следует игнорировать> {% comment %} djlint:on {% endcomment %} +``` + +или как комментарий в стиле javascript - + +```html +{{ /* djlint:off */ }} <плохой html, который следует игнорировать> {{ /* djlint:on */ }} +``` + +или как комментарий в стиле golang - + +```html +{{!-- djlint:off --}} <плохой html, который следует игнорировать> {{!-- djlint:on --}} +``` + +{% endraw %} + +## Игнорирование правил + +Определенные правила linter можно игнорировать, добавив имя правила в открывающий тег игнорируемого блока. + +{% raw %} +```html +{# djlint:off H025,H026 #} +

    +{# djlint:on #} + + +

    + + +{% comment %} djlint:off H025 {% endcomment %} +

    +{% comment %} djlint:on {% endcomment %} + +{{!-- djlint:off H025 --}} +

    +{{!-- djlint:on --}} + +{{ /* djlint:off H025 */ }} +

    +{{ /* djlint:on */ }} +``` +{% endraw %} diff --git a/src/djlint/helpers.py b/src/djlint/helpers.py index 99162e8..5cb7921 100644 --- a/src/djlint/helpers.py +++ b/src/djlint/helpers.py @@ -100,3 +100,21 @@ def inside_ignored_block(config: Config, html: str, match: re.Match) -> bool: ) ) ) + + +def inside_ignored_rule(config: Config, html: str, match: re.Match, rule: str) -> bool: + """Check if match is inside an ignored pattern.""" + for rule_regex in config.ignored_rules: + for ignored_match in list( + re.finditer( + re.compile(rule_regex, re.DOTALL | re.IGNORECASE | re.VERBOSE), + html, + ) + ): + if ( + rule in list(set(re.split(r"\s|,", ignored_match.group(1).strip()))) + and ignored_match.start(0) <= match.start() + and match.end(0) <= ignored_match.end() + ): + return True + return False diff --git a/src/djlint/lint.py b/src/djlint/lint.py index a71ca49..5a43847 100644 --- a/src/djlint/lint.py +++ b/src/djlint/lint.py @@ -5,7 +5,7 @@ from typing import Dict, List import regex as re -from .helpers import inside_ignored_block +from .helpers import inside_ignored_block, inside_ignored_rule from .settings import Config flags = { @@ -88,7 +88,11 @@ def lint_file(config: Config, this_file: Path) -> Dict: open_tags.insert(0, match) for match in open_tags: - if inside_ignored_block(config, html, match) is False: + if ( + inside_ignored_block(config, html, match) is False + and inside_ignored_rule(config, html, match, rule["name"]) + is False + ): errors[filename].append( { "code": rule["name"], @@ -105,7 +109,11 @@ def lint_file(config: Config, this_file: Path) -> Dict: ), html, ): - if inside_ignored_block(config, html, match) is False: + if ( + inside_ignored_block(config, html, match) is False + and inside_ignored_rule(config, html, match, rule["name"]) + is False + ): errors[filename].append( { "code": rule["name"], diff --git a/src/djlint/settings.py b/src/djlint/settings.py index a020ccf..9205b1a 100644 --- a/src/djlint/settings.py +++ b/src/djlint/settings.py @@ -579,6 +579,18 @@ class Config: | ^---[\s\S]+?--- """ + self.ignored_rules: List[str] = [ + # html comment + r".*?(?=)", + # django/jinja/nunjucks + r"{\#\s*djlint\:\s*off(.+?)\#}.*?(?={\#\s*djlint\:\s*on\s*\#})", + r"{%\s*comment\s*%\}\s*djlint\:off(.*?)\{%\s*endcomment\s*%\}.*?(?={%\s*comment\s*%\}\s*djlint\:on\s*\{%\s*endcomment\s*%\})", + # handlebars + r"{{!--\s*djlint\:off(.*?)--}}.*?(?={{!--\s*djlint\:on\s*--}})", + # golang + r"{{-?\s*/\*\s*djlint\:off(.*?)\*/\s*-?}}.*?(?={{-?\s*/\*\s*djlint\:on\s*\*/\s*-?}})", + ] + self.ignored_inline_blocks: str = r""" | <(script|style).*?\ diff --git a/tests/test_linter/test_linter.py b/tests/test_linter/test_linter.py index e278414..f02412b 100644 --- a/tests/test_linter/test_linter.py +++ b/tests/test_linter/test_linter.py @@ -762,3 +762,32 @@ H025 2:4 Tag seems to be an orphan.

    H025 2:12 Tag seems to be an orphan.

    """ in result.output ) + + +def test_ignoring_rules(runner: CliRunner, tmp_file: TextIO) -> None: + write_to_file( + tmp_file.name, + b"""{# djlint:off H025,H026 #} +

    +{# djlint:on #} + + +

    + + +{% comment %} djlint:off H025 {% endcomment %} +

    +{% comment %} djlint:on {% endcomment %} + +{{!-- djlint:off H025 --}} +

    +{{!-- djlint:on --}} + +{{ /* djlint:off H025 */ }} +

    +{{ /* djlint:on */ }} + +""", + ) + result = runner.invoke(djlint, [tmp_file.name]) + assert "H025" not in result.output