Twig Tags

Square Online page templates support the following core Twig tags:

Square Online page templates support the Twig template language (version 3.x). For your convenience, excerpts of documentation for supported Twig tags are provided here under the BSD 3-Clause “New” or “Revised” License. Copyright © 2009-present by the Twig Team.

apply

The apply tag allows you to apply Twig filters on a block of template data:

{% apply upper %}
    This text becomes uppercase
{% endapply %}

You can also chain filters and pass arguments to them:

{% apply lower|escape('html') %}
    <strong>SOME TEXT</strong>
{% endapply %}

{# outputs "&lt;strong&gt;some text&lt;/strong&gt;" #}

Back to top


block

Blocks are used for inheritance and act as placeholders and replacements at the same time. They are documented in detail in the documentation for the extends tag.

Block names must consist of alphanumeric characters, and underscores. The first char can’t be a digit and dashes are not permitted.

See also:

Back to top


do

The do tag works exactly like the regular variable expression ({{ ... }}) just that it doesn’t print anything:

{% do 1 + 2 %}

Back to top


embed

The embed tag combines the behavior of include and extends. It allows you to include another template’s contents, just like include does. But it also allows you to override any block defined inside the included template, like when extending a template.

Think of an embedded template as a “micro layout skeleton”.

{% embed "teasers_skeleton.twig" %}
    {# These blocks are defined in "teasers_skeleton.twig" #}
    {# and we override them right here:                    #}
    {% block left_teaser %}
        Some content for the left teaser box
    {% endblock %}
    {% block right_teaser %}
        Some content for the right teaser box
    {% endblock %}
{% endembed %}

The embed tag takes the idea of template inheritance to the level of content fragments. While template inheritance allows for “document skeletons”, which are filled with life by child templates, the embed tag allows you to create “skeletons” for smaller units of content and re-use and fill them anywhere you like.

Since the use case may not be obvious, let’s look at a simplified example. Imagine a base template shared by multiple HTML pages, defining a single block named “content”:

┌─── page layout ─────────────────────┐
│                                     │
│           ┌── block "content" ──┐   │
│           │                     │   │
│           │                     │   │
│           │ (child template to  │   │
│           │  put content here)  │   │
│           │                     │   │
│           │                     │   │
│           └─────────────────────┘   │
│                                     │
└─────────────────────────────────────┘

Some pages (“foo” and “bar”) share the same content structure - two vertically stacked boxes:

┌─── page layout ─────────────────────┐
│                                     │
│           ┌── block "content" ──┐   │
│           │ ┌─ block "top" ───┐ │   │
│           │ │                 │ │   │
│           │ └─────────────────┘ │   │
│           │ ┌─ block "bottom" ┐ │   │
│           │ │                 │ │   │
│           │ └─────────────────┘ │   │
│           └─────────────────────┘   │
│                                     │
└─────────────────────────────────────┘

While other pages (“boom” and “baz”) share a different content structure - two boxes side by side:

┌─── page layout ─────────────────────┐
│                                     │
│           ┌── block "content" ──┐   │
│           │                     │   │
│           │ ┌ block ┐ ┌ block ┐ │   │
│           │ │"left" │ │"right"│ │   │
│           │ │       │ │       │ │   │
│           │ │       │ │       │ │   │
│           │ └───────┘ └───────┘ │   │
│           └─────────────────────┘   │
│                                     │
└─────────────────────────────────────┘

Without the embed tag, you have two ways to design your templates:

  • Create two “intermediate” base templates that extend the master layout template: one with vertically stacked boxes to be used by the “foo” and “bar” pages and another one with side-by-side boxes for the “boom” and “baz” pages.

  • Embed the markup for the top/bottom and left/right boxes into each page template directly.

These two solutions do not scale well because they each have a major drawback:

  • The first solution may indeed work for this simplified example. But imagine we add a sidebar, which may again contain different, recurring structures of content. Now we would need to create intermediate base templates for all occurring combinations of content structure and sidebar structure… and so on.

  • The second solution involves duplication of common code with all its negative consequences: any change involves finding and editing all affected copies of the structure, correctness has to be verified for each copy, copies may go out of sync by careless modifications etc.

In such a situation, the embed tag comes in handy. The common layout code can live in a single base template, and the two different content structures, let’s call them “micro layouts” go into separate templates which are embedded as necessary:

Page template foo.twig:

{% extends "layout_skeleton.twig" %}

{% block content %}
    {% embed "vertical_boxes_skeleton.twig" %}
        {% block top %}
            Some content for the top box
        {% endblock %}

        {% block bottom %}
            Some content for the bottom box
        {% endblock %}
    {% endembed %}
{% endblock %}

And here is the code for vertical_boxes_skeleton.twig:

<div class="top_box">
    {% block top %}
        Top box default content
    {% endblock %}
</div>

<div class="bottom_box">
    {% block bottom %}
        Bottom box default content
    {% endblock %}
</div>

The goal of the vertical_boxes_skeleton.twig template being to factor out the HTML markup for the boxes.

The embed tag takes the exact same arguments as the include tag:

{% embed "base" with {'foo': 'bar'} %}
    ...
{% endembed %}

{% embed "base" with {'foo': 'bar'} only %}
    ...
{% endembed %}

{% embed "base" ignore missing %}
    ...
{% endembed %}

As embedded templates do not have “names”, auto-escaping strategies based on the template name won’t work as expected if you change the context (for instance, if you embed a CSS/JavaScript template into an HTML one). In that case, explicitly set the default auto-escaping strategy with the autoescape tag.

See also:

Back to top


extends

The extends tag can be used to extend a template from another one.

Twig does not support multiple inheritance. So you can only have one extends tag called per rendering.

Let’s define a base template, base.html, which defines a simple HTML skeleton document:

<!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 %}
                &copy; Copyright 2011 by <a href="http://domain.invalid/">you</a>.
            {% endblock %}
        </div>
    </body>
</html>

In this example, the block tags define four blocks that child templates can fill in.

All the block tag does is to tell the template engine that a child template may override those portions of the template.

Child Template

A child template might look like this:

{% extends "base.html" %}

{% 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 on my awesome homepage.
    </p>
{% endblock %}

The extends tag is the key here. It tells the template engine that this template “extends” another template. When the template system evaluates this template, first it locates the parent. The extends tag should be the first tag in the template.

Note that since the child template doesn’t define the footer block, the value from the parent template is used instead.

You can’t define multiple block tags with the same name in the same template. This limitation exists because a block tag works in “both” directions. That is, a block tag doesn’t just provide a hole to fill - it also defines the content that fills the hole in the parent. If there were two similarly-named block tags in a template, that template’s parent wouldn’t know which one of the blocks’ content to use.

If you want to print a block multiple times you can however use the block function:

<title>{% block title %}{% endblock %}</title>
<h1>{{ block('title') }}</h1>
{% block body %}{% endblock %}

Parent Blocks

It’s possible to render the contents of the parent block by using the parent function function. This gives back the results of the parent block:

{% block sidebar %}
    <h3>Table Of Contents</h3>
    ...
    {{ parent() }}
{% endblock %}

Named Block End-Tags

Twig allows you to put the name of the block after the end tag for better readability (the name after the endblock word must match the block name):

{% block sidebar %}
    {% block inner_sidebar %}
        ...
    {% endblock inner_sidebar %}
{% endblock sidebar %}

Block Nesting and Scope

Blocks can be nested for more complex layouts. Per default, blocks have access to variables from outer scopes:

{% for item in seq %}
    <li>{% block loop_item %}{{ item }}{% endblock %}</li>
{% endfor %}

Block Shortcuts

For blocks with little content, it’s possible to use a shortcut syntax. The following constructs do the same thing:

{% block title %}
    {{ page_title|title }}
{% endblock %}
{% block title page_title|title %}

Dynamic Inheritance

Twig supports dynamic inheritance by using a variable as the base template:

{% extends some_var %}

If the variable evaluates to a \Twig\Template or a \Twig\TemplateWrapper instance, Twig will use it as the parent template::

// {% extends layout %}

$layout = $twig->load('some_layout_template.twig');

$twig->display('template.twig', ['layout' => $layout]);

You can also provide a list of templates that are checked for existence. The first template that exists will be used as a parent:

{% extends ['layout.html', 'base_layout.html'] %}

Conditional Inheritance

As the template name for the parent can be any valid Twig expression, it’s possible to make the inheritance mechanism conditional:

{% extends standalone ? "minimum.html" : "base.html" %}

In this example, the template will extend the “minimum.html” layout template if the standalone variable evaluates to true, and “base.html” otherwise.

How do blocks work?

A block provides a way to change how a certain part of a template is rendered but it does not interfere in any way with the logic around it.

Let’s take the following example to illustrate how a block works and more importantly, how it does not work:

{# base.twig #}
{% for post in posts %}
    {% block post %}
        <h1>{{ post.title }}</h1>
        <p>{{ post.body }}</p>
    {% endblock %}
{% endfor %}

If you render this template, the result would be exactly the same with or without the block tag. The block inside the for loop is just a way to make it overridable by a child template:

{# child.twig #}
{% extends "base.twig" %}

{% block post %}
    <article>
        <header>{{ post.title }}</header>
        <section>{{ post.text }}</section>
    </article>
{% endblock %}

Now, when rendering the child template, the loop is going to use the block defined in the child template instead of the one defined in the base one; the executed template is then equivalent to the following one:

{% for post in posts %}
    <article>
        <header>{{ post.title }}</header>
        <section>{{ post.text }}</section>
    </article>
{% endfor %}

Let’s take another example: a block included within an if statement:

{% if posts is empty %}
    {% block head %}
        {{ parent() }}

        <meta name="robots" content="noindex, follow">
    {% endblock head %}
{% endif %}

Contrary to what you might think, this template does not define a block conditionally; it just makes overridable by a child template the output of what will be rendered when the condition is true.

If you want the output to be displayed conditionally, use the following instead:

{% block head %}
    {{ parent() }}

    {% if posts is empty %}
        <meta name="robots" content="noindex, follow">
    {% endif %}
{% endblock head %}

See also:

Back to top


for

Loop over each item in a sequence. For example, to display a list of users provided in a variable called users:

<h1>Members</h1>
<ul>
    {% for user in users %}
        <li>{{ user.username|e }}</li>
    {% endfor %}
</ul>

A sequence can be either an array or an object implementing the Traversable interface.

If you do need to iterate over a sequence of numbers, you can use the .. operator:

{% for i in 0..10 %}
    * {{ i }}
{% endfor %}

The above snippet of code would print all numbers from 0 to 10.

It can be also useful with letters:

{% for letter in 'a'..'z' %}
    * {{ letter }}
{% endfor %}

The .. operator can take any expression at both sides:

{% for letter in 'a'|upper..'z'|upper %}
    * {{ letter }}
{% endfor %}

If you need a step different from 1, you can use the range function instead.

The loop variable

Inside of a for loop block you can access some special variables:

Variable Description
loop.index The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex The number of iterations from the end of the loop (1 indexed)
loop.revindex0 The number of iterations from the end of the loop (0 indexed)
loop.first True if first iteration
loop.last True if last iteration
loop.length The number of items in the sequence
loop.parent The parent context
{% for user in users %}
    {{ loop.index }} - {{ user.username }}
{% endfor %}

The else clause

If no iteration took place because the sequence was empty, you can render a replacement block by using else:

<ul>
    {% for user in users %}
        <li>{{ user.username|e }}</li>
    {% else %}
        <li><em>no user found</em></li>
    {% endfor %}
</ul>

Iterating over Keys

By default, a loop iterates over the values of the sequence. You can iterate on keys by using the keys filter:

<h1>Members</h1>
<ul>
    {% for key in users|keys %}
        <li>{{ key }}</li>
    {% endfor %}
</ul>

Iterating over Keys and Values

You can also access both keys and values:

<h1>Members</h1>
<ul>
    {% for key, user in users %}
        <li>{{ key }}: {{ user.username|e }}</li>
    {% endfor %}
</ul>

Iterating over a Subset

You might want to iterate over a subset of values. This can be achieved using the slice filter:

<h1>Top Ten Members</h1>
<ul>
    {% for user in users|slice(0, 10) %}
        <li>{{ user.username|e }}</li>
    {% endfor %}
</ul>

Back to top


from

The from tag imports macro names into the current namespace. The tag is documented in detail in the documentation for the macro tag.

Back to top


if

The if statement in Twig is comparable with the if statements of PHP.

In the simplest form you can use it to test if an expression evaluates to true:

{% if online == false %}
    <p>Our website is in maintenance mode. Please, come back later.</p>
{% endif %}

You can also test if an array is not empty:

{% if users %}
    <ul>
        {% for user in users %}
            <li>{{ user.username|e }}</li>
        {% endfor %}
    </ul>
{% endif %}

If you want to test if the variable is defined, use if users is defined instead.

You can also use not to check for values that evaluate to false:

{% if not user.subscribed %}
    <p>You are not subscribed to our mailing list.</p>
{% endif %}

For multiple conditions, and and or can be used:

{% if temperature > 18 and temperature < 27 %}
    <p>It's a nice day for a walk in the park.</p>
{% endif %}

For multiple branches elseif and else can be used like in PHP. You can use more complex expressions there too:

{% if product.stock > 10 %}
    Available
{% elseif product.stock > 0 %}
    Only {{ product.stock }} left!
{% else %}
    Sold-out!
{% endif %}

Here are the edge cases rules to determine if an expression is true or false: | Value | Boolean evaluation | |:——|:——|
| empty string | false | | numeric zero | false | | NAN (Not A Number) | true | | INF (Infinity) | true | | whitespace-only string | true | | string “0” or ‘0’ | false | | empty array | false | | null | false | | non-empty array | true | | object | true |

Back to top


import

The import tag imports macro names in a local variable. The tag is documented in detail in the documentation for the macro tag.

Back to top


macro

Macros are comparable with functions in regular programming languages. They are useful to reuse template fragments to not repeat yourself.

Macros are defined in regular templates.

Imagine having a generic helper template that define how to render HTML forms via macros (called forms.html):

{% macro input(name, value, type = "text", size = 20) %}
    <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}"/>
{% endmacro %}

{% macro textarea(name, value, rows = 10, cols = 40) %}
    <textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols }}">{{ value|e }}</textarea>
{% endmacro %}

Each macro argument can have a default value (here text is the default value for type if not provided in the call).

Macros differ from native PHP functions in a few ways:

  • Arguments of a macro are always optional.

  • If extra positional arguments are passed to a macro, they end up in the special varargs variable as a list of values.

But as with PHP functions, macros don’t have access to the current template variables.

You can pass the whole context as an argument by using the special _context variable.

Importing Macros

There are two ways to import macros. You can import the complete template containing the macros into a local variable (via the import tag) or only import specific macros from the template (via the from tag).

To import all macros from a template into a local variable, use the import tag:

{% import "forms.html" as forms %}

The above import call imports the forms.html file (which can contain only macros, or a template and some macros), and import the macros as items of the forms local variable.

The macros can then be called at will in the current template:

<p>{{ forms.input('username') }}</p>
<p>{{ forms.input('password', null, 'password') }}</p>

Alternatively you can import names from the template into the current namespace via the from tag:

{% from 'forms.html' import input as input_field, textarea %}

<p>{{ input_field('password', '', 'password') }}</p>
<p>{{ textarea('comment') }}</p>

When macro usages and definitions are in the same template, you don’t need to import the macros as they are automatically available under the special _self variable:

<p>{{ _self.input('password', '', 'password') }}</p>

{% macro input(name, value, type = "text", size = 20) %}
   <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}"/>
{% endmacro %}

Macros Scoping

The scoping rules are the same whether you imported macros via import or from.

Imported macros are always local to the current template. It means that macros are available in all blocks and other macros defined in the current template, but they are not available in included templates or child templates; you need to explicitly re-import macros in each template.

Imported macros are not available in the body of embed tags, you need to explicitly re-import macros inside the tag.

When calling import or from from a block tag, the imported macros are only defined in the current block and they override macros defined at the template level with the same names.

When calling import or from from a macro tag, the imported macros are only defined in the current macro and they override macros defined at the template level with the same names.

Checking if a Macro is defined

You can check if a macro is defined via the defined test:

{% import "macros.twig" as macros %}

{% from "macros.twig" import hello %}

{% if macros.hello is defined -%}
    OK
{% endif %}

{% if hello is defined -%}
    OK
{% endif %}

Named Macro End-Tags

Twig allows you to put the name of the macro after the end tag for better readability (the name after the endmacro word must match the macro name):

{% macro input() %}
    ...
{% endmacro input %}

Back to top


set

Inside code blocks you can also assign values to variables. Assignments use the set tag and can have multiple targets.

Here is how you can assign the bar value to the foo variable:

{% set foo = 'bar' %}

After the set call, the foo variable is available in the template like any other ones:

{# displays bar #}
{{ foo }}

The assigned value can be any valid :ref:Twig expression <twig-expressions>:

{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
{% set foo = 'foo' ~ 'bar' %}

Several variables can be assigned in one block:

{% set foo, bar = 'foo', 'bar' %}

{# is equivalent to #}

{% set foo = 'foo' %}
{% set bar = 'bar' %}

The set tag can also be used to ‘capture’ chunks of text:

{% set foo %}
    <div id="pagination">
        ...
    </div>
{% endset %}

If you enable automatic output escaping, Twig will only consider the content to be safe when capturing chunks of text.

Note that loops are scoped in Twig; therefore a variable declared inside a for loop is not accessible outside the loop itself:

{% for item in list %}
   {% set foo = item %}
{% endfor %}

{# foo is NOT available #}

If you want to access the variable, just declare it before the loop:

{% set foo = "" %}
{% for item in list %}
   {% set foo = item %}
{% endfor %}

{# foo is available #}

Back to top


verbatim

The verbatim tag marks sections as being raw text that should not be parsed. For example to put Twig syntax as example into a template you can use this snippet:

{% verbatim %}
    <ul>
    {% for item in seq %}
        <li>{{ item }}</li>
    {% endfor %}
    </ul>
{% endverbatim %}

Back to top


with

Use the with tag to create a new inner scope. Variables set within this scope are not visible outside of the scope:

{% with %}
    {% set foo = 42 %}
    {{ foo }} {# foo is 42 here #}
{% endwith %}
foo is not visible here any longer

Instead of defining variables at the beginning of the scope, you can pass a hash of variables you want to define in the with tag; the previous example is equivalent to the following one:

{% with { foo: 42 } %}
    {{ foo }} {# foo is 42 here #}
{% endwith %}
foo is not visible here any longer

{# it works with any expression that resolves to a hash #}
{% set vars = { foo: 42 } %}
{% with vars %}
    ...
{% endwith %}

By default, the inner scope has access to the outer scope context; you can disable this behavior by appending the only keyword:

{% set bar = 'bar' %}
{% with { foo: 42 } only %}
    {# only foo is defined #}
    {# bar is not defined #}
{% endwith %}