craft-twig-guidelines
Skill2 starsChanged 8 months agoMITView on GitHub
Twig coding standards and conventions for Craft CMS 5 templates. Covers variable naming, null handling, whitespace control, include isolation, Craft Twig helpers ({% tag %}, tag(), attr(), |attr, svg()), and collect() usage. Triggers on: any Twig template creation or review, .twig files, {% include %}, {% extends %}, {% tag %}, collect(), props.get(), .implode(), attr(), |attr filter, svg(), ?? operator, whitespace control, template coding standards, Twig best practices, naming conventions for Twig, currentSite, siteUrl, craft.entries, .eagerly(), .collect. Not for Twig architecture patterns (use craft-site) or PHP code (use craft-php-guidelines). Always use when writing, editing, or reviewing any Craft CMS Twig template code.
1 other project uses a version of this, 1 of them edited.
Adopted by
Most recently taken up by
- michtio/craftcms-claude-skillsedited, first seen Jul 28, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 1
- michtio/craftcms-claude-skills★ 8232% same
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository7 other files it gives its agents.
- project-template/CLAUDE.mdCLAUDE.md
- reference/CLAUDE.mdCLAUDE.md
- craftcmsSkill
- craft-content-modelingSkill
- craft-php-guidelinesSkill
- craft-siteSkill
- ddevSkill
The file
We split this skill into the rules it gives an agent
9 rules. About 0 are common, 2 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
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 21
Use web_fetch on specific doc pages when something isn't covered here.
- Very specific: line 42
No abbreviations: element not el, button not btn, navigation not nav, description not desc.
- Very specific: line 45
If you need a multi-word variable, reconsider whether you're over-specifying.
- Very specific: line 46
If truly unavoidable, use snake_case over camelCase: hero_image over heroImage.
- Very specific: line 79
Use {%- and {{- for whitespace trimming.
- Distinctive: line 95
Not every tag needs it — use where visible output whitespace matters.
- Very specific: line 99
Every {% include %} MUST use only.
- Very specific: line 120
Never use {% macro %} for UI components.
- Distinctive: line 141
Every component file gets a section header comment:
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 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
Coding conventions for Twig templates in Craft CMS 5 projects. These apply to all Twig code — atomic components, views, layouts, builders, partials.
For Twig architecture patterns (atomic design, routing, builders), see the
craft-site skill. 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 web_fetch on specific doc pages when something isn't covered here.
Variable Naming
Single-word, descriptive, lowercase. No camelCase in Twig unless absolutely unavoidable.
{# Correct #}
{% set heading = entry.title %}
{% set image = entry.heroImage.one() %}
{% set items = navigation.links.all() %}
{% set element = props.get('url') ? 'a' : 'span' %}
{# Wrong #}
{% set heroHeading = entry.title %}
{% set heroImg = entry.heroImage.one() %}
{% set navItems = navigation.links.all() %}
{% set el = props.get('url') ? 'a' : 'span' %}No abbreviations: element not el, button not btn, navigation not nav,
description not desc.
If you need a multi-word variable, reconsider whether you're over-specifying.
If truly unavoidable, use snake_case over camelCase: hero_image over heroImage.
Null Handling
?? only. Always. No exceptions.
{# Correct #}
{% set heading = entry.heading ?? '' %}
{% set image = entry.heroImage.one() ?? null %}
{{ props.get('label') ?? 'Default' }}
{# Wrong — custom Twig extension, not portable #}
{% set heading = entry.heading ??? '' %}
{# Wrong — verbose, unnecessary #}
{% if entry.heading is defined and entry.heading is not null %}
{% if entry.heading is not defined %}Twig 3.21.x (Craft 5) does not have the nullsafe operator (?.). That requires
Twig 3.23+. Use ?? and ternaries instead:
{# Can't do this yet #}
{{ entry?.author?.fullName }}
{# Do this instead #}
{{ entry.author.fullName ?? '' }}Whitespace Control
Use {%- and {{- for whitespace trimming. Never use {%- minify -%}.
{# Correct — surgical whitespace control #}
{%- set heading = entry.title -%}
{%- if heading -%}
{{- heading -}}
{%- endif -%}
{# Wrong — deprecated minification approach #}
{%- minify -%}
{% set heading = entry.title %}
{%- endminify -%}Apply whitespace control on tags that produce unwanted blank lines in output. Not every tag needs it — use where visible output whitespace matters.
Include Isolation
Every {% include %} MUST use only. No exceptions.
{# Correct — explicit, isolated #}
{%- include '_atoms/buttons/button--primary' with {
text: entry.title,
url: entry.url,
} only -%}
{# Wrong — ambient variables leak in #}
{%- include '_atoms/buttons/button--primary' with {
text: entry.title,
url: entry.url,
} -%}Without only, a component can silently depend on variables from its parent
scope, creating invisible coupling.
No Macros for Components
Never use {% macro %} for UI components. Macros don't support extends/block
and their scoping model differs from includes.
{# Wrong — macro for a component #}
{% macro button(text, url) %}
<a href="{{ url }}">{{ text }}</a>
{% endmacro %}
{# Correct — include with isolation #}
{%- include '_atoms/buttons/button--primary' with {
text: text,
url: url,
} only -%}Macros are acceptable for utility functions that return strings (e.g., formatting helpers), not for rendering UI.
Comment Headers
Every component file gets a section header comment:
{# =========================================================================
Component Name
Brief description of what this component does.
========================================================================= #}Props files, variant files, views, layouts — all get headers. The =========
separator matches the PHP convention from craft-php-guidelines.
Craft Twig Helpers
{% tag %} — Polymorphic Elements
Primary tool for rendering elements whose tag name depends on props.
{%- set element = props.get('url') ? 'a' : 'span' -%}
{%- tag element with {
class: classes.implode(' '),
href: props.get('url') ?? false,
target: props.get('target') ?? false,
rel: props.get('rel') ?? false,
aria: {
label: props.get('label') ?? false,
},
} -%}
{{ props.get('text') }}
{%- endtag -%}Rules:
- Variable name must be descriptive:
element,heading,wrapper. Neverel,hd. falseomits an attribute entirely from the rendered HTML.nullalso omits. Usefalsewhen explicitly excluding,nullwhen absent.classaccepts arrays with automatic falsy filtering.ariaanddataaccept nested hashes that expand toaria-*/data-*attributes.
tag() — Inline Element Function
For simple elements without complex inner content:
{{ tag('span', { class: 'sr-only', text: '(opens in new window)' }) }}
{{ tag('img', { src: image.url, alt: image.title, loading: 'lazy' }) }}
{{ tag('i', { class: ['fa-solid', icon], aria: { hidden: 'true' } }) }}text:key = HTML-encoded content.html:key = raw HTML content (trusted input only).- Self-closing elements (
img,input,br) handled automatically.
attr() — Attribute Strings
For building attributes in non-tag contexts:
<div{{ attr({ class: ['card', active ? 'card--active'], data: { id: entry.id } }) }}>Returns a space-prefixed attribute string. Same false-means-omit and class
array filtering as {% tag %}.
|attr Filter
For merging attributes onto existing HTML strings:
{{ svg('@webroot/icons/check.svg')|attr({ class: 'w-4 h-4', aria: { hidden: 'true' } }) }}|parseAttr Filter
For extracting attributes from an HTML string into a hash for manipulation:
{% set attributes = '<div class="foo" data-id="1">'|parseAttr %}
{# attributes = { class: 'foo', data: { id: '1' } } #}|append Filter
For adding content to an element string:
{{ svg('@webroot/icons/logo.svg')|append('<title>Company Logo</title>', 'replace') }}svg() Function
{{ svg('@webroot/icons/logo.svg') }}
{{ svg(entry.svgField.one()) }}Combine with |attr for classes and aria attributes. Use |append for
accessible labels inside the SVG.
collect() Conventions
collect() wraps a Twig hash into a Collection object. Primary use cases:
Props collection
{%- set props = collect({
heading: heading ?? null,
content: content ?? null,
utilities: utilities ?? null,
}) -%}
{# Access with get() #}
{{ props.get('heading') }}
{{ props.get('size', 'text-base') }}
{# Merge additional props #}
{%- set props = props.merge({ icon: icon ?? null }) -%}Class collection (named keys)
{%- set classes = collect({
layout: 'flex items-center gap-2',
color: 'bg-brand-primary text-white',
hover: 'hover:bg-brand-accent',
utilities: props.get('utilities'),
}) -%}
class="{{ classes.implode(' ') }}"Null values in collect() produce harmless extra spaces when joined — browsers
normalize whitespace in class attributes. Use classes.filter(v => v).implode(' ')
if you want pristine output for devMode inspection, but plain implode(' ')
is fine for production.
Entry queries as Collections
{# .collect instead of .all() when you need Collection methods #}
{%- set entries = craft.entries.section('blog').eagerly().collect -%}
{%- set featured = entries.filter(e => e.featured).first -%}Common Pitfalls
???operator — custom Twig extension from older projects. Not portable. Use??.- camelCase variables —
iconPosition→ justposition. Single descriptive words. - 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. options.xpattern — old macro convention. Use direct variable names.
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.

