Tags
Tags are a fundamental part of Twig's syntax, used to control the flow of templates and perform various actions, such as looping, including other templates, and setting variables. Tags typically enclose blocks of code that manipulate the structure or content of your templates.
Common Twig Tags
{% if %} {% else %}
The if
tag is used to execute a block of code only if a certain condition is met. The else
tag provides an alternative block of code to execute if the condition is not met.
{% if global.customer.id %}
Welcome, {{ global.customer.first_name }}!
{% else %}
Welcome!
{% endif %}
{% for %}
The for
tag is used to loop over an array or object. It's useful for iterating through lists, such as products or categories.
{% for product in products %}
<div>{{ product.title }}</div>
{% endfor %}
{% set %}
The set
tag is used to assign values to variables within your template. This is useful for storing values that you want to reuse later in the template.
{% set discount = 10 %}
The discount is {{ discount }}%.
{% include %}
The include
tag is used to insert the contents of one template into another. This allows for reusing components across multiple templates, such as headers, footers, or product listings.
{% include 'header.twig' %}
{% block %} {% endblock %}
The block
tag defines a block of content that can be overridden in . It's commonly used in conjunction with template inheritance to allow customisation of certain sections within a base template.
{% block content %}
<h1>Welcome to our website</h1>
{% endblock %}
{% extends %}
The extends
tag is used to indicate that a template inherits from a parent template. This allows for creating a base layout that can be extended and customised by child templates.
{% extends 'page.twig' %}
{% import %}
The import
tag allows you to import macros from another template. Macros are reusable snippets of code that can be used across multiple templates.
{% import 'macros/html.twig' as html %}
{{ html.stylesheet(asset_url('scss/theme.css')) }}
{% filter %}
The filter
tag is used to apply a filter to a block of content.
{{ "this text will be uppercase" | upper }}