Tran Cao Minh
MinhTC's Blog

Follow

MinhTC's Blog

Follow
Why did Shopware 6 choose Twig as its PHP template?

Why did Shopware 6 choose Twig as its PHP template?

Tran Cao Minh's photo
Tran Cao Minh
ยทOct 28, 2022ยท

2 min read

Play this article

Table of contents

  • Overview
  • Basic syntax
  • Shopware's twig functions
  • Conclusion

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:

  1. Full-Featured: Multiple inheritances, blocks, ...
{% extends "layout.html" %}

{% block content %}
    Content of the page...
{% endblock %}
  1. 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) }}
  1. 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.

  1. Syntax variations
{{ 'Hello' }} {# print 'Hello' #}
{% if user.age < 18 %} {# excute statement #}
{# comment inside #}
  1. Control structures
{% if users|length > 0 %}
  <ul>
    {% for u in users %}
      <li>{{ u.username }}</li>
    {% endfor %}
  </ul>
{% endif %}
  1. Bocks (Sections of templating code with a unique name)
{% block footer %}
   <p>Make by MinhTC</p>
{% endblock %}
  1. Functions
{{ dump(page.detail) }}
  1. 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:

  1. 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 %}
  1. 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 ๐Ÿ˜„.

ย 
Share this