Twig Guide

Master Twig templating to create powerful themes.

Twig Basics

Twig is a flexible, fast, and secure template engine for PHP. It's the templating engine used by Symfony and PteroCA.

Variables:

{{ variable }}
{{ user.username }}
{{ product.name }}

Filters:

{{ text|upper }}
{{ date|date('Y-m-d') }}
{{ price|number_format(2, '.', ',') }}
{{ content|raw }}  {# Render HTML #}

Functions:

{{ asset('assets/theme/my-theme/css/style.css') }}
{{ path('route_name') }}
{{ url('route_name', {id: 123}) }}

Control Structures:

{% if condition %}
    ...
{% elseif other_condition %}
    ...
{% else %}
    ...
{% endif %}

{% for item in items %}
    {{ item.name }}
{% else %}
    No items found
{% endfor %}

Blocks and Inheritance

Define blocks (in parent template):

Override blocks (in child template):

Including Templates

Macros (Reusable Functions)

Define macro:

Use macro:

Common PteroCA Variables

Available in most templates:

Asset Function

Translation Function

Useful Twig Filters

Filter
Description
Example

upper

Convert to uppercase

{{ 'hello'|upper }} → HELLO

lower

Convert to lowercase

{{ 'HELLO'|lower }} → hello

capitalize

Capitalize first letter

{{ 'hello'|capitalize }} → Hello

title

Title case

{{ 'hello world'|title }} → Hello World

length

Get length

{{ items|length }}

date

Format date

{{ date|date('Y-m-d') }}

default

Default value if empty

{{ variable|default('N/A') }}

join

Join array

{{ items|join(', ') }}

slice

Get subset

{{ text|slice(0, 100) }}

trim

Remove whitespace

{{ text|trim }}

raw

Output unescaped HTML

{{ html|raw }}

Useful Twig Tests

Best Practices

  1. Escape output by default (Twig does this automatically)

  2. Use |raw sparingly - only for trusted HTML

  3. Keep logic minimal - use controllers for complex logic

  4. Extract reusable parts - use includes and macros

  5. Name blocks clearly - makes overriding easier

  6. Comment complex sections - helps future maintainers

  7. Test with different data - ensure templates handle edge cases

Common Patterns

Conditional CSS classes:

Loop with alternating classes:

Safe navigation (null-safe):

Multiple conditions:

Debugging

Dump variable:

Print all variables:

Note: Dumps only work in development mode (APP_ENV=dev).

External Resources

Last updated