Basic syntax
Twig is a "template engine" the template contains variables and functions which get replaced when the template is evaluated it also uses tags to manage the template logic. In other words, Twig helps buliding interactive interfaces with feasible connections to the underlying programming. It's meant to be used with a js class that sends the variables to be displayed on an HTML page, and the HTML just displays the data.
:::tip[A thing to know!]
Twilight uses Twig as its "template engine"
:::
📙 What you'll learn
In this article, you will learn the basic syntax of Twig.
Delimiters
Twig defines three kinds of 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
<!DOCTYPE html>
<html>
<head>
<title>My Twilight Template</title>
</head>
<body>
My name is {{ name }} and I love Twilight.
My favorite flavors of cookies are:
<ul>
{% for cookie in cookies %}
<li>{{ cookie.flavor }}</li>
{% endfor %}
</ul>
<h1>Cookies are the best!</h1>
</body>
</html>
Twig Basic Tags
Tags tell Twig what it needs to do. It allows setting which code Twig should handle and which code it should ignore during evaluation.
There are several different kinds of tags, and each has its own specific syntax that sets them apart. These are the tags to be used:
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
As an initial point, set
tags are used to assign values to variables within blocks:
{% set Lion = 'King' %}
{{Lion}} /* Lion will be King */
extends & blocks
Template inheritance is one of twigs perks. It allows setting a base code that contains all the elements for your website and defining blocks that inheritance can override from child templates.
Let's define a base template, master.twig
, which defines an HTML skeleton document that might be used for a two-column page:
<!DOCTYPE html>
<html>
<head>
{% block head %}
<link rel="stylesheet" href="style.css"/>
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
{% block footer %}
© Copyright 2011 by <a href="http://domain.invalid/">you</a>.
{% endblock %}
</div>
</body>
</html>
In this example, the 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.
A child template might look like this:
{% extends "master.twig" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ parent() }}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome to my awesome homepage.
</p>
{% endblock %}
blocks
block
is used for inheritance and acts as placeholders and replacements at the same time.
The block function allowes to print a block mutiple times in templates that uses inheritance.
<h1>{{ block('title') }}</h1>
{% block body %}
{% endblock %}
The defines test cheks if a block exists in the context of the current template:
{% if block("footer") is defined %}
{% endif %}
{% if block("footer", "common_blocks.twig") is defined %}
{% endif %}
The block function can also be used to display one block from another template:
{{ block("title", "common_blocks.twig") }}
include
include
is used to include a file's content inside a block tag.
{% block header %}
{{ include 'lion' }}
{% endblock %}
for-loop
for-loop
is used to loop through multiple items of array or hash and produces results based on the expression.
For example, the below code loops through products array using for-loop
which is passed from the server. Then prints out the products id.
{% for product in products %}
<div class="card shadow">
<a href="/products/{{ product.id }}">View The Product</a>
</div>
{% endfor %}
if-else
Executes the code if the expression in place is true
and assigns fallback conditions if it's false
.
{% if order %}
<div>{{ order.id }}</div>
{% endif %}
Filters
Twig filters allow you to apply functionality to the variable on the left side of the pipe (|) symbol. They are handy when dealing with manipulating text or variables.
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.
Examples of built-in Twig filters include raw
, length
, date
, split
, join
, lower
, slice
, and many more.
Examples:
- The raw filter marks the value as being "safe", which means that in an environment with automatic escaping enabled this variable will not be escaped if raw is the last filter applied to it:
{% autoescape %}
{{ var|raw }} {# var won't be escaped #}
{% endautoescape %}
- The
length
filter returns the number of items of a sequence or mapping, or the length of a string.
{% if products|length > 10 %}
<h3>{{ product.name }}</h3>
{% endif %}
- The
date
filter formats a date to a given format:
{{ comment.published_at|date("m/d/Y") }}
{# outputs 4/4/2022 #}
- The
split
filter splits a string by the given delimiter and returns a list of strings:
```js
{% set foo = "one,two,three"|split(',') %}
{# foo contains ['one', 'two', 'three'] #}
### Functions
Twig functions are another way to implement functionality in Twig. They are similar to filters; however, rather than acting on a variable via the pipe (|) symbol, you would call these functions directly and pass in any attributes they support between the parentheses after the function name.
Examples of built-in Twig filters include `block`, `dump`, `parent`, `random`, `range`, and more.
Examples:
- The `random` filter returns a random value.
in the example below it returns a random number
```js
<div class="price">
{{ random(10) }}
{# random(10) returns a number from 0 to 10 #}
</div>
- The
range
filter returns a list containing an arithmetic progression of integers:
{% for i in range(0, 3) %}
{{ i }},
{% endfor %}
{# outputs 0, 1, 2, 3, #}
You are now prepared to use the tags commonly used by twig to build your theme.