Skip to main content

Rule 32 - Twig: Code formatting

How a Twig template file is laid out: header, prop preparation, HTML whitespace inside opening tags, and the vertical rhythm of the rendered markup.

Rule 31 covers prop naming. Rule 32 covers how the file is written - where prop setup sits, how defaults are declared, how attributes are stacked on elements, how trim markers keep the rendered HTML clean, and the blank-line structure between logical sections.

Rules​

File structure​

32.1. A component Twig file MUST begin with a Twig docblock comment describing the component and its variables. The docblock MUST list every declared prop with its type.

{#
Button component.

Variables:
- content (string): Visible button text.
- is_disabled (boolean): Renders the disabled attribute.
- is_loading (boolean): Adds aria-busy="true" for loading state.
- classes (array): CSS classes for the root element.
- attributes (object): HTML attributes for the root element.
#}

32.2. After the docblock, a single blank line MUST separate the docblock from the prop-preparation header.

32.3. The prop-preparation header MUST contain every {% set %} call that normalizes or derives values from props. No {% set %} calls MAY appear inside the markup body except those scoped to a narrow {% block %} or loop, or to the body {% if %} that gates the whole render, for a value that gate makes safe to compute.

Defaults via the default filter​

32.4. Each declared prop MUST be normalized on its own line at the top of the header using the |default(...) filter. Scalar props default to an empty string, false, 0, or an appropriate fallback. Collection props default to [] or {}.

{% set content = content|default('') %}
{% set is_disabled = is_disabled|default(false) %}
{% set is_loading = is_loading|default(false) %}
{% set classes = classes|default([]) %}
{% set attributes = attributes|default({}) %}

32.5. is defined and is iterable guards MUST NOT be used for prop defaulting. |default() is the canonical mechanism. The is defined form is permitted only where the prop carries a three-state meaning (undefined vs. false vs. true) that |default() cannot express. A default of null combined with an is not null check MAY also be used where 0 is a valid value distinct from "unset".

{# Wrong - |default handles this #}
{% if classes is defined and classes is iterable %}
{% set class_list = classes %}
{% endif %}

{# Correct #}
{% set classes = classes|default([]) %}

Enum validation​

32.6. Enum props MUST be validated inline using the ternary pattern from Rule 31.9, placed in the header block immediately after the prop's |default() line.

{% set type = type|default('default') %}
{% set type = type in ['default', 'featured'] ? type : 'default' %}

Derived values​

32.7. Values derived from multiple props (composed class lists, ARIA strings, conditional markers) MUST be declared in the header, separated from the prop normalization by a single blank line.

{% set content = content|default('') %}
{% set is_disabled = is_disabled|default(false) %}
{% set classes = classes|default([]) %}
{% set attributes = attributes|default({}) %}

{% set button_type = attributes.type|default('button') %}
{% set classes = ['btn']|merge(classes) %}
{% if attributes.class is defined %}{% set classes = classes|merge([attributes.class]) %}{% endif %}
{% set busy_label = (is_loading and not content) ? 'Please wait…' : '' %}

32.8. Class-list composition MUST reuse the classes prop variable rather than introducing a second name (class_list, css_classes, etc.). The classes prop is the canonical local name for the element's CSS class list; build it up with |merge rather than shadowing it under a different identifier. Rule 31.10 reserves class / className as top-level prop names, but consumers MAY still pass attributes: { class: '…' } - the component MUST merge that value into the final class list so the override takes effect.

{# Correct - reuse `classes` #}
{% set classes = ['card']|merge(classes) %}
{% if size %}{% set classes = classes|merge([size]) %}{% endif %}
{% if attributes.class is defined %}{% set classes = classes|merge([attributes.class]) %}{% endif %}

{# Wrong - introduces a redundant `class_list` variable #}
{% set class_list = ['card']|merge(classes) %}

{# Wrong - string composition is harder to filter and reorder #}
{% set classes = '%s %s'|format('card', size) %}

32.9. {% set %} lines that do not render output MUST NOT carry {%- -%} trim markers. Trim markers belong on the {{ ... }} expressions and {% if %} / {% for %} blocks that DO render output - not on variable assignment.

HTML - vertical rhythm​

32.10. A single blank line MUST separate the prop-preparation header from the first line of markup.

32.11. An opening tag with 2 or fewer conditional attributes MAY stay on a single line. With 3 or more, the tag MUST break onto one conditional attribute per line; the always-rendered attributes, static or interpolated, share the first line per 32.12, because a line break inside an unconditional attribute would render as whitespace in the tag.

{# Two attributes - single line #}
<a href="{{ url }}" class="{{ classes|join(' ') }}">{{- text -}}</a>

{# Three+ attributes - one per line #}
<button type="{{ button_type }}"
{%- if classes %} class="{{ classes|join(' ') }}"{% endif %}
{%- if is_disabled %} disabled{% endif %}
{%- if is_loading %} aria-busy="true"{% endif %}
{%- for key, value in attributes %}{% if key not in ['type', 'class'] %} {{ key }}="{{ value }}"{% endif %}{% endfor -%}
>
{{- content -}}
</button>

Attribute whitespace in multi-line opening tags​

Goal. The source code lists one attribute per line for readability; the rendered HTML stays compact, with a single space between attributes and no newlines inside the opening tag. Trim markers do the collapsing.

32.12. In a multi-line opening tag:

  • The first line MUST be <element optionally followed by one or more always-rendered static attributes. This anchors the output so the element's name and first attribute sit on one line in the rendered HTML.
  • Every subsequent attribute line MUST start with {%- to absorb the preceding newline and indent.
  • The body of each conditional or loop MUST begin with a single leading space before the attribute name (that space becomes the separator in the rendered output).
  • The last conditional or loop before the closing > MUST end with -%} to absorb the trailing newline before >.
<details
{%- if classes %} class="{{ classes|join(' ') }}"{% endif %}
{%- if name %} name="{{ name }}"{% endif %}
{%- if open %} open{% endif %}
{%- for key, value in attributes %}{% if key not in ['class', 'name', 'open'] %} {{ key }}="{{ value }}"{% endif %}{% endfor -%}
>

Rendered HTML (all truthy): <details class="..." name="..." open data-x="...">

32.13. The closing > of a multi-line opening tag MUST sit on its own line at the same indent as the opening <. The trim on the final conditional or loop handles the whitespace collapse; > does not need its own trim marker.

32.14. Passthrough attribute loops MUST follow this exact shape:

{%- for key, value in attributes %}{% if key not in ['reserved-1', 'reserved-2'] %} {{ key }}="{{ value }}"{% endif %}{% endfor -%}
  • {%- prefix absorbs the preceding newline.
  • The condition is a nested {% if %} inside the loop body, not an inline if on the {% for %} tag. The Twig.js npm package does not correctly parse the inline if filter on for loops.
  • Leading space inside the {% if %} body separates attributes.
  • No trailing space after "{{ value }}" - the next iteration supplies its own leading space.
  • -%} on {% endfor %} collapses the trailing newline before > when the loop is the last item in the opening tag.
  • The reserved-name list MAY be hoisted into a header variable ({% if key not in upload_skip_attrs %}) when it is long or shared between 2 loops.

Text nodes and inline expressions​

32.15. Text nodes between inline or multi-line element boundaries MUST use {{- -}} trim markers to avoid stray whitespace around the rendered content.

<span class="badge">{{- content -}}</span>

<button ...>
{{- content -}}
</button>

32.16. {{ variable }} expressions inside attribute values carry no trim markers. The quotes delimit the value, and a trim marker strips template whitespace around the tag, never whitespace inside the variable's own value.

<a href="{{ url }}" aria-label="{{ label }}">

Semantic vertical rhythm​

32.17. A single blank line MUST separate each independent {% block %} or top-level {% if %} section inside the markup. Sibling sections MUST NOT run together without a separator.

{% block content_top %}
{% if content_top %}
<div class="card-top">{{- content_top -}}</div>
{% endif %}
{% endblock %}

{% block content_body %}
{% if title or content %}
<div class="card-body">
{% if title %}<h3>{{- title -}}</h3>{% endif %}
{% if content %}<p>{{- content -}}</p>{% endif %}
</div>
{% endif %}
{% endblock %}

{% block content_bottom %}
{% if content_bottom %}
<div class="card-bottom">{{- content_bottom -}}</div>
{% endif %}
{% endblock %}

Includes​

32.18. {% include %} calls with three or more keys MUST break onto one key per line, with a trailing comma after the last key. Two or fewer keys MAY stay on a single line.

{# Two keys - single line #}
{% include '@components/icon/icon.twig' with { name: 'close', size: 'sm' } only %}

{# Three or more - one per line #}
{% include '@components/button/button.twig' with {
content: 'Submit',
classes: ['accent'],
attributes: { type: 'submit' },
} only %}

32.19. {% include %} calls MUST pass with_context: false (the only keyword) whenever the included template does not need the outer scope. Semetrika components are self-contained - they declare every prop they use and must not reach into the caller's context.

32.20. The tag form {% include 'tpl' with { ... } only %} MUST be used. The function form {{ include('tpl', { ... }, with_context: false) }} MUST NOT be used. Both forms render identically in PHP Twig, but only the tag form is supported by twig.js (used by Storybook) without a parser shim - keeping the codebase on a single form removes the build-time transformation step.

{# Correct - tag form #}
{%- include '@components/icon/icon.twig' with { symbol: 'close' } only -%}

{# Wrong - function form #}
{{- include('@components/icon/icon.twig', { symbol: 'close' }, with_context: false) -}}

Whitespace and final newline​

32.21. Twig files MUST end with a final newline (see Rule 51.5).

32.22. No trailing whitespace MUST appear on any line.

32.23. Indentation MUST be two spaces. Tabs MUST NOT be used.

Automated enforcement​

32.24. yarn lint-twig runs twig-cs-fixer over every .twig file under src/ and is invoked from yarn lint; yarn lint-twig --fix rewrites what it can. It covers 32.21-32.23 plus delimiter spacing, operator spacing, trailing commas, and quote style. The ruleset in .twig-cs-fixer.php drops two defaults that contradict rules above - IncludeFunctionRule (32.20) and PunctuationSpacingRule (32.18).

The wrapper at scripts/lint-twig.mjs skips when PHP or the phar is absent, so a contributor without PHP still gets a passing yarn lint.


Enforced by

32.1, 32.20 by yarn cli 32 (findHeaderDrift, findFunctionFormIncludes in packages/cli/src/rules/32.js). 32.2-32.19, 32.21-32.24 are review only. See enforcement.md.