Table of contents
Overview
When working with Shopware, it appeared and changed my look at the PHP template engine. Twig has many advanced. In my opinion, when coming from React, some features that make me really impressive are:
- Full-Featured: Multiple inheritances, blocks, ...
{% extends "layout.html" %}
{% block content %}
Content of the page...
{% endblock %}
- Secure: Sandboxing "Where the user has access to a limited defined by the developer", automatic output-escaping.
{% autoescape "html" %}
{{ var }}
{{ var|raw }} {# var won't be escaped #}
{{ var|escape }} {# var won't be doubled-escaped #}
{% endautoescape %}
{{ include('page.html', sandboxed = true) }}
- Template-oriented syntax: Shortcuts for common patterns, like a default text displayed when iterating with an empty array.
{% for u in users %}
* {{ u.name }}
{% else %}
No users have been found.
{% endfor %}
Basic syntax
From it advanced, so if you want to have a quick look at Twig. This is my honor to share with you some basic syntax that I have learned. You can find more in Twig's document.
- Syntax variations
{{ 'Hello' }} {# print 'Hello' #}
{% if user.age < 18 %} {# excute statement #}
{# comment inside #}
- Control structures
{% if users|length > 0 %}
<ul>
{% for u in users %}
<li>{{ u.username }}</li>
{% endfor %}
</ul>
{% endif %}
- Bocks (Sections of templating code with a unique name)
{% block footer %}
<p>Make by MinhTC</p>
{% endblock %}
- Functions
{{ dump(page.detail) }}
- Filter (Functions used as pipes)
<p>{{ user.firstname|trans|upper }}</p>
Shopware's twig functions
Twig is a powerful PHP template engine. But it does not stop at it. When including Twig, Shopware also increases its strength with its Twig functions. Some really useful functions with me are:
- sw_extends
Based Twigs extends
Inherit a template and extend it using
{% block %}{% endblock %}
{% sw_extends '@Storefront/storefront/layout/header/logo.html.twig' %}
{% block layout_header_logo_image %}
{{ parent() }}
<h1>Some adding text to logo</h1>
{% endblock %}
- sw_include (Include another template)
- With variables
{% sw_include '@Storefront/example.html.twig' with {
'name': 'value'
} %}
- Dynamic templates
{% if template is empty %}
{% set template = 'error-page' %}
{% endif %}
{% sw_include "@Storefront/" ~ template ".html.twig" ignore missing %}
Conclusion
Well, congratulation. With this basic knowledge, you can start your Twig code in any Shopware project. Thanks for reading and happy coding day 😄.