Skip to main content

Twig CS Fixer

https://github.com/VincentLanglet/Twig-CS-Fixer

The missing checkstyle for twig!

Twig CS Fixer aims to be what phpcs is to php. It checks your codebase for violations on coding standards.

Vortex comes with a pre-configured Twig CS Fixer ruleset for Drupal projects.

Usage

Check for violations

# Lint all front-end code: Twig, JavaScript and CSS.
ahoy lint-fe

Fix violations

# Fix all front-end lint issues.
ahoy lint-fe-fix

Configuration

See configuration reference.

All global configuration takes place in the .twig-cs-fixer.php file.

Targets include custom modules and themes.

Adding or removing targets:

$finder = new TwigCsFixer\File\Finder();
$finder->in(__DIR__ . '/web/modules/custom');
$finder->in(__DIR__ . '/web/themes/custom');

Ignoring

Excluding target directories takes place in the .twig-cs-fixer.php file - $finder->exclude() removes directories from the set of linted files rather than disabling a rule:

$finder->exclude('myCustomDirectory');

Every error has an identifier in the form A.B:C:D, where:

  • A: the rule short name (mainly made from the class name)
  • B: the error identifier (like the error level or a specific name)
  • C: the line the error occurs on
  • D: the position of the token in that line

All 4 parts are optional: A, A.B, A.B:C, A.B:C:D, A:C, A:C:D and A::D all work. To find the identifier of an error you want to ignore, run the linter command with the --debug option.

To ignore all Twig CS Fixer rules within a file, place in the file header:

{# twig-cs-fixer-disable #}

To ignore a specific rule within a file, place in the file header:

{# twig-cs-fixer-disable A.B:C:D #}

Twig CS Fixer does not support ignoring of the code blocks.

To ignore only the current line:

{{ token }} {# twig-cs-fixer-disable-line A.B:C:D #}

To ignore only the next line:

{# twig-cs-fixer-disable-next-line A.B:C:D #}
{{ token }}

Continuous integration

Twig CS Fixer runs in the lint job of the continuous integration pipeline and fails the build on violations.

Ignoring failures

Set the VORTEX_CI_TWIG_CS_FIXER_IGNORE_FAILURE environment variable to 1. The tool still runs and reports violations.

➡️ See Continuous integration > Ignore tool failures