2025-06-12
Twig
Twig is a modern template engine for PHP which compiles templates down to plain optimized PHP code. Used in Craft CMS amongst others.
Tips
<body> tag with many attributes
{% set bodyAttributes = {
id: siteName|kebab,
class: [
craft.app.config.general.devMode ? "devMode",
entry is defined ? "type-" ~ entry.type,
entry is defined and entry.backgroundColor is defined and entry.backgroundColor|length ? entry.backgroundColor : "color-4",
product is defined ? "type-product"
],
data: {
controller: "global " ~ stimulusPageController|default(''),
}
} %}
<body {{ attr(bodyAttributes) }}>
How does attr() function works? #
Let's summarize what attr() function does with data passed to it:
- Contents of
classarray - strings representing single classes - get properly concatenated while keeping necessary whitespace between each class. - Object
styleconsisting of CSS property-value pairs is transformed into properstyleattribute. - Contents of
dataobject are transformed into multiple data-attributes. In the case of multidimensional arrays indataobject, an array is serialized so it can be later retrieved from single data-attribute by JavaScript. - Objects with a single boolean value, like
hidden, are rendered as empty HTML attributes (without value) - if boolean value istrueor are not rendered at all - if boolean value isfalse. - Rest of objects with string value are just rendered as corresponding HTML attributes - like
idfor example.
HTML tag with many attributes (simpler version)
If there are many attributes to be set on a tag, you can use Twig to achieve more readable code.
{% set buttonAttributes = {
'class': 'menu',
'data-mobile-navigation-target': 'button',
'data-action': 'mobile-navigation#toggle',
'aria-label': 'Open navigation'
} %}
<button {{ attr(buttonAttributes) }}>
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</button>
HTML tag with many classes
If there is an HTML tag with many classes, you can also use Twig.
{% set classes = [
'block',
'py-12 px-2',
'border-2 border-white',
'text-center text-white',
'leading-none',
'no-underline uppercase tracking-wide'
] %}
<div class="{{classes|join(' ')}}"></div>
Tag
Sometimes it can be practical to create an HTML element directly from Twig.
{{ tag('p'), {
text: textVariable1 ?? textVariable2,
class: classVariable ?? "text"
}) }}
Use a variable as text
If you need to use a variable as plain text.
{% set animals = {
dogs: ['Fido', 'Buster', 'Pluto']
} %}
{% for key in animals %}
{% set output = include(template="animals/**#{key}**.twig") %}
{% endfor %}
Variables in context
All variables that are available in the current context:
{% dd _context | keys %}