craft-twig-guidelines
Skill90 starsChanged 4 months agoMITView on GitHub
Twig coding standards and conventions for Craft CMS 5 templates. ALWAYS load this skill when writing, editing, or reviewing any .twig file in a Craft CMS project, even for small edits. Covers: variable naming (camelCase, no abbreviations), null handling (?? operator, ??? with empty-coalesce plugin), whitespace control ({%- trimming, NOT {%- minify -%}), include isolation (always 'only'), Craft Twig helpers ({% tag %}, tag(), attr(), |attr, |parseAttr, |append, svg()), collect() for props and class collections, .implode(), ========= comment headers on component files, and pitfalls (snake_case, macros as components, hardcoded colors).
In this repository18 other files it gives its agents.
- docs/agents.mdAGENTS.md
- project-template/CLAUDE.mdCLAUDE.md
- reference/CLAUDE.mdCLAUDE.md
- craft-cloudSkill
- craftcmsSkill
- craft-content-modelingSkill
- craft-fortrabbitSkill
- craft-garnishSkill
- craft-gated-buildSkill
- craft-mcpSkill
- craft-pestSkill
- craft-php-guidelinesSkill
- craft-plugin-releaseSkill
- craft-pluginsSkill
- craft-project-setupSkill
- craft-siteSkill
- ddevSkill
- servdSkill
The file
We split this skill into the rules it gives an agent
7 rules. About 0 are common, 0 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 33
Use WebFetch on specific doc pages when something isn't covered here.
- Very specific: line 48
Every
{% include %}usesonly: No exceptions: without it the component silently depends on parent variables. - Very specific: line 65
Polymorphic elements: use {% tag element with {…} %} with a descriptive variable (element, wrapper).
- Very specific: line 67
Data manipulation: default to collect() chains.
- Very specific: line 68
Output: every user-facing string through |t('category').
- Very specific: line 69
Copy style: no em-dashes (—) or en-dashes (–) in template text or |t strings.
- Very specific: line 89
Grepping output for a
|e('js')-escaped phrase: every space becomes a \uXXXX sequence, so grep or assert on a single token.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Twig Coding Standards — Craft CMS 5
Craft Version of This Project
!sh ${CLAUDE_SKILL_DIR}/scripts/craft-version.sh
If no Craft version line appears above, establish the version before any version-specific advice: craftcms/cms in composer.lock for a site, the lowest version the craftcms/cms constraint in composer.json allows for a plugin, or ask. Then check it against the version tags in this skill ([5.10+], [changed 5.12], [seomatic 5.1+]).
Coding conventions for Twig templates in Craft CMS 5 projects. These apply to all Twig code — atomic components, views, layouts, builders, partials.
Companion Skills — Always Load Together
craft-site— Template architecture and component patterns (atomic design, routing, builders). Required when creating or editing components, layouts, views, or builders.craft-content-modeling— Content architecture. Required when template code involves element queries, field access, or section decisions.
For PHP coding standards, see craft-php-guidelines.
Documentation
- Twig in Craft: https://craftcms.com/docs/5.x/development/twig.html
- Template tags: https://craftcms.com/docs/5.x/reference/twig/tags.html
- Template functions: https://craftcms.com/docs/5.x/reference/twig/functions.html
- Twig 3 docs: https://twig.symfony.com/doc/3.x/
Use WebFetch on specific doc pages when something isn't covered here.
Reference Files
| Task | Read | ~Tokens |
Correct/wrong examples for naming, ??/???/?., whitespace, only on include/render/include_only(), macros, comment headers, collect() classes, copy style; long form of the pitfalls | references/core-conventions.md | ~2,450 |
{% tag %}, tag(), attr(), |attr, |parseAttr, |append, svg(), url(…, false), heading()/h() [5.10+], filter additions [5.10+], collect() vs array filters, |t/|purify/|raw, {% js %}/{% css %}, |e('js') escaping | references/craft-helpers.md | ~1,950 |
Upgrading to 5.12 [changed 5.12]: case filters follow the site language, Twig 3.29 to 3.31 deprecations (spaceless, macro calls, matches) | references/craft-5-12-changes.md | ~800 |
Rules
- Naming: camelCase, single word when context allows (
heading,buttonText). Never snake_case, never abbreviations:elementnotel,buttonnotbtn,navigationnotnav,descriptionnotdesc. - Nulls:
??is the default.???only whennystudio107/craft-emptycoalesceornystudio107/craft-seomaticis already installed (checkcomposer.json; never install one just for???).?.for chains whose intermediate links may be null (entry?.author?.fullName ?? 'Anonymous'), not for a single property. Neveris defined and is not null. - Whitespace:
{%-/{{-/-%}where output whitespace matters. Never{%- minify -%}. Every
{% include %}usesonly. No exceptions: without it the component silently depends on parent variables. The same goes for{% render %}[5.12+]:{# Correct #} {%- render entry.contentBlocks with { theme: 'dark' } only -%}[5.12+] Before 5.12 the tag fails the whole template at compile time: use
{{ entry.contentBlocks.render({ theme: 'dark' }) }}. Inside the partial,entryis the rendered element, not the page entry.include_only()[5.12+] is the function form; [5.12+] before 5.12:include(…, with_context = false). Partial lookup:craft-site(references/element-partials.md).- No
{% macro %}for UI components (no extends/block, different scoping). Macros only for string-returning helpers. Every component file gets a header (props, variants, views, layouts too), with the same
=========separator as the PHP convention:{# ========================================================================= Component Name Brief description of what this component does. ========================================================================= #}- Polymorphic elements use
{% tag element with {…} %}with a descriptive variable (element,wrapper);falseomits an attribute.tag(),attr(),|attr,svg():references/craft-helpers.md. - Class strings:
collect({})with camelCase named keys, one key per style concern, joined with.implode(' '). Never'flex ' ~ extraClass. Full patterns:craft-site(references/twig-collections.md,references/tailwind-conventions.md). - Data manipulation: default to
collect()chains; a bare|filter/|maponly for one trivial inline step. There is no|indexBy(use|indexor.keyBy()). - Output: every user-facing string through
|t('category');|purifyfor untrusted HTML,|rawonly for trusted field output;{% js %}/{% css %}instead of hand-written<script>/<style>; never ship{% dd %}/dump(). - Copy style: no em-dashes (—) or en-dashes (–) in template text or
|tstrings; use commas, colons, parentheses, or a plain hyphen, and write ranges as "4 to 10". Twig comments are exempt. Grep for—and–before finishing.
Common Pitfalls
???operator without the plugin — requiresnystudio107/craft-emptycoalesceornystudio107/craft-seomatic. Checkcomposer.jsonbefore using. Default to??.- snake_case variables — use camelCase:
heroImagenothero_image. - Missing
only— silent variable leaking, invisible coupling. {%- minify -%}— deprecated. Use{%-whitespace control.- Abbreviations —
el,btn,nav,desc,ctr→ spell it out. is not defined— verbose null checking.??handles it.- Macros as components — wrong scoping, no extends/block support.
- Hardcoded colors in class strings —
bg-yellow-600→bg-brand-accent. - String concatenation for classes —
'flex ' ~ extraClass→ usecollect({})with named keys. is empty/|defaulton Craft Models [changed 5.10]: from 5.10 everyyii\base\Modelcounts as non-empty, so{{ user|default('Guest') }}renders the user. Test the property:{% if entry.title is empty %}.options.xpattern — old macro convention. Use direct variable names.- Blocks inside conditionals: invalid Twig. Put the
{% if %}inside the{% block %}. - Hardcoded
/adminCP URL:cpTriggeris configurable. UsecpUrl(). - Em/en-dashes in user-facing copy: see Copy style above.
- Twig has no
instanceof: branch onobject.hasProperty()/hasMethod()or have PHP pass a discriminator. - Per-request output inside
{% cache %}(CSP nonce,csrfInput(), active classes, language-switcher URLs) is frozen at the first render. See thecraft-siteskill'stemplate-caching.md. - Grepping output for a
|e('js')-escaped phrase: every space becomes a\uXXXXsequence, so grep or assert on a single token. Seereferences/craft-helpers.md. {% render %}on a site below 5.12 [5.12+]: unknown tag, the whole template fails to compile. Use.render()where the template must also run on older releases.- Appending alpha to a colour [changed 5.12]:
{{ entry.brand }}80orentry.brand.hex ~ '1a'breaks once a Color field returns an 8-digit hex (translucent palette colours, or custom colours with opacity allowed). Usergb({{ entry.brand.rgbChannels }} / 50%)[5.12+] orentry.brand.rgba[5.12+];entry.brand.getHex(false) ~ '80'works on every version. Before 5.12: hex was always 6-digit. - Macros called without parentheses [5.12+]:
{{ macros.label }}is deprecated in Twig 3.29 and a syntax error in Twig 4. Write{{ macros.label() }}. |upper/|loweron identifiers [changed 5.12]: casing follows the site language, so a Turkish site lowercasesItoı. Pass('en')for codes and handles. Seereferences/craft-5-12-changes.md.heading()/h()on an older site:heading()andh()need [5.10+]. Before 5.10: build the tag from the level yourself.{{ tag('h' ~ level, { text: title }) }}(tag()takes an attributes array;textis encoded,htmlis not) or{% tag 'h' ~ level with { class: 'text-xl' } %}Subsection{% endtag %}. Don't shipheading()/h()to a site below 5.10.url()withfalse[5.11+] strips every query param from an absolute URL. Before 5.11:siteUrl(craft.app.request.pathInfo).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

