HOWTO.twig - raynaldmo/HOWTO GitHub Wiki

Twig Templating

Twig is a templating language for PHP

  • It is a tool used to output variables inside HTML

Resources

Twig Delimiters

  • Use {# #} delimiter for comments
  • Use {{ }} delimiter for printing variables
  • Use {% %} delimiter for control (if, for) structures
  • Put space after opening delimiter and before closing delimiter
    • {# comment #}
    • {{ variable }}
    • {% if (condition) %}

Comments

  • Use {# #} delimiter
{# This is a comment #}

{# note: disabled template because we no longer use this
  {% for user in users %}
        ...
  {% endfor %}
#}

Printing Variables

  • Use {{ }} delimiter

Print variables or results of an expression

# Print out variable
{{ name_of_variable }}

{{ title_prefix }}

# Print out the results of an expression
{{ name_of_variable|name_of_filter }}

<title>{{ head_title|safe_join(' | ') }}</title>

# Print out a variable appended with a function
<div{{ attributes.addClass('banner') }}></div>

Arrays and Objects

  • Variables
  • Twig has a special syntax for accessing array and object values
  • array keys, object properties and object methods are called variable attributes
  • dot (.) operator is used to access variable attributes (variable can be an array or object)
  • Using PHP object operator -> isn't allowed
  • Use dot operator to access object properties and methods (or attribute() function)
# Print associative array value
# $page = [ 'sidebar_right' => '<div>content</div>' ];
{{ page.sidebar_right }}

# Print indexed array value
{{ array_var.1 }}

# This also works
{{ array_var[1] }}

# Use square bracket syntax for arrays if array key has hyphen (-) or pound (#) 
{{ array_var['#key'] }}
{{ array_var['data-one'] }}
{{ content.field_image.0['#item'].alt }}
{{ array_var[random(4)] }}

# Alternately can user attribute() function
{{ attribute(array_var, 'data-one') }}

# Print multi-level/multi-dimensional array value
{{ array_variable.key1.key2 }}
{{ array_variable.0.key1.0 }}

# Combining dot and square bracket syntax is valid
{{ variable.0['#hash'].key }}

{{ content.field_image.0['#item'].alt }} {# Alt attribute #}
{{ content.field_image.0['#item'].width }} {# Width attribute #}
{{ content.field_image.0['#item'].height }} {# Height attribute #}

Twig Tags

    apply
    autoescape
    block
    deprecated
    do
    embed
    extends
    filter
    flush
    for
    from
    if
    import
    include
    macro
    sandbox
    set
    spaceless
    use
    verbatim
    with
  • Twig tags are used inside the {% %} delimiter (e.g {% if online == false %} .... {% endif %})

Setting Variables

{% set string_var = 'string1' %}
{% set array_var = [1, 2] %}
{% set array_var = ['zero' => 0, 'one' => 1] %}

Control Structures

  • Use {% %} delimiter

Conditional Statements

  • Use if else elseif endif tags
# Test scalar variable
{% if online == false %}
  <p>The website is in maintenance mode</p>
{% endif %}

# Test if array is empty
{% if users %}
  ...
{% endif %}

{% if page_footer %}
  <footer role="contentinfo">
    {{ page_footer }}
  </footer>
{% endif %}

# Multiple branches
{% if user.status == 'active' %}
...
{% elseif %}
...
{% else %}
...
{% endif %}

Loops

  • Use for endfor tags
<ul class='blog-post__tags field__items'>
  {% for item in items %}
    <li>{{ item.content }}</li>
  {% endfor %}
</ul>

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

# Use .. operator to iterate over a sequence of numbers or strings
{% for i in 0..10 %}
  * {{ i }}
{% endfor %}

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

# Iterate over array keys - use key filter
<h1>Members</h1>
<ul>
  {% for key in users|keys %}
    <li>{{ key }}</li>
  {% endfor %}
</ul>

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

# Limit items returned in iteration (use if clause)
<ul>
  {% for user in users if user.active %}
    <li>{{ user.username|e }}</li>
  {% endfor %}
</ul>

# Use else clause to handle empty values
<ul>
  {% for user in users %}
    <li>{{ user.username|e }}</li>
  {% else %}
    <li><em>no user found</em></li>
  {% endfor %}
</ul>

Ternary Operator ?:

{{ foo ? 'yes' : 'no' }}
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}

Null-coalescing Operator: ??

{# returns the value of foo if it is defined and not null, 'no' otherwise #}
{{ foo ?? 'no' }}

White Space Control

Filters

Functions

Template Inheritance

  • Template inheritance allows you to build a base skeleton template that contains all the common elements of your site and defines blocks that child templates can override.

  • Template Inheritance

Including other Templates

  • Use include() function to add template code/markup to specific pages
  • Template code/markup that should be added to all pages should be added in base template
  • Including other Templates
⚠️ **GitHub.com Fallback** ⚠️