Basic syntax
A thing to know!
📙 What you'll learn
Delimiters
{{ ... }}
prints the result of an expression evaluation.{% ... %}
to execute statements, such as for-loops.{# ... #}
to add comments in the templates. These comments aren't included on the rendered page.Basic Twig Template
Twig Basic Tags
Basic Tags | Description |
---|---|
set | Assigns values to variables. |
extends & blocks | Sets the base code for the site and defines the blocks that inherit from child blocks. |
blocks | Used for inheritance and act as placeholders and replacements at the same time |
include | Used to include a file's content inside a block tag. |
for-loop | Used to loop over multiple items in an array using the for tag. |
if-else | Executes the code if the expression in place is true and assigns fallback conditions if it's false . |
set
set
tags are used to assign values to variables within blocks:
extends & blocks
master.twig
, which defines an HTML skeleton document that might be used for a two-column page:
block
tags define blocks that child templates can fill in. All the block
tag tells the template engine that a child template may override those portions of the template.
blocks
block
is used for inheritance and acts as placeholders and replacements at the same time.
include
include
is used to include a file's content inside a block tag.
for-loop
for-loop
is used to loop through multiple items of array or hash and produces results based on the expression.for-loop
which is passed from the server. Then prints out the products id.
if-else
true
and assigns fallback conditions if it's false
.
Filters
The first argument to the filter is always the item on the left, but subsequent arguments can be passed in parentheses. Filters have some special capabilities, including being environmentally aware.
raw
, length
, date
, split
, join
, lower
, slice
, and many more.
length
filter returns the number of items of a sequence or mapping, or the length of a string.
date
filter formats a date to a given format:
split
filter splits a string by the given delimiter and returns a list of strings:
Functions
block
, dump
, parent
, random
, range
, and more.random
filter returns a random value.in the example below it returns a random number
range
filter returns a list containing an arithmetic progression of integers:
Modified at 2025-03-04 12:54:02