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
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
Escape output by default (Twig does this automatically)
Use
|rawsparingly - only for trusted HTMLKeep logic minimal - use controllers for complex logic
Extract reusable parts - use includes and macros
Name blocks clearly - makes overriding easier
Comment complex sections - helps future maintainers
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).
Related Guides
Overriding Templates - Customize specific templates
Theme Structure - File organization
JavaScript - Add interactivity
Testing - Quality assurance
External Resources
Last updated