Twig for front-enders

Lauri Eskola

What is Twig?


  {#
  /*
   * @file
   * Defines list theme component.
   *
   * Available variables:
   * - items: A list of list items.
   */
  #}
  <ul class="list">
    {% for item in items %}
      <li class="list__item">
        {{ item }}
      </li>
    {% endfor %}
  </ul>

Example Twig file

The “Say Something” Syntax: {{ ... }}

The “Do Something” Syntax: {% ... %}

The Comment Syntax: {# ... #}

Printing variables using Twig magic

{{ node.title }}

  
  // Array key.
  $node['title'];

  // Object property.
  $node->title;

  // Object method.
  $node->title();

  // Object get method convention.
  $node->getTitle();

  // Object is method convention.
  $node->isTitle();
              

Sounds slow?

 

If you need to render a lot of Twig files, install Twig PHP package

Configuring Twig for debugging

sites/default/services.yml


  parameters:
    twig.config:    
      debug: true

Theme suggestions in the HTML as comments:


  <!-- THEME DEBUG -->
  <!-- THEME HOOK: 'node' -->
  <!-- FILE NAME SUGGESTIONS:
     * node--article--teaser.html.twig
     * node--article.html.twig
     * node--teaser.html.twig
     x node.html.twig
  -->
  <!-- BEGIN OUTPUT from 'core/themes/bartik/templates/node.html.twig' -->

Debugging variables


  {{ kint(node) }}

Twig filters

Meant to manipulate a variable. Takes the first parameter from the variable before "|".


  {% set text = 'Kitten' %}
  {# Print variable using length filter. #}
  {{ text|length }} {# Returns: 6 #}

Example

Twig functions

Functions in Twig are much like PHP functions


  {% if date(cookie.created) < date('-2 days') %}
    {# Eat it! #}
  {% endif %}

Example

All Twig functions and filters need to be mapped in a Twig Extension

 

http://twig.sensiolabs.org/doc/functions/index.html

Twig Include

node--teaser.html.twig


  {{ content|without('links') }}

  {% include "link.html.twig" with {
      link: node.url,
      text: 'Read more'|t,
    } only
  %}

link.html.twig


  <a href="{{ url }}">{{ text }}</a>

Twig blocks

page.html.twig


  <h1>Title</h1>

  {% block content %}
    This will be overridden by page--front.html.twig
  {% endblock %}

  {% block footer %}
    Another block
  {% endblock %}

page--front.html.twig


  {% extends "page.html.twig" %}
  {% block content %}
    Modify a small part of the parent template
  {% endblock %}

Twig Embed

content.html.twig


  <h1>{{ title }}</h1>

  {% block left %}
  {% endblock %}

  {% block right %}
  {% endblock %}

  {% embed "content.html.twig" with {
      title: title 
    } only 
  %}
    {% block left %}
      {{ content.left }}
    {% endblock %}

    {% block right %}
      {{ content.right }}
    {% endblock %}
  {% endembed %}

page.html.twig

Twig for frontenders

By lauriii

Twig for frontenders

  • 1,463