Twig
02 / 02

Twig Fundamentals: Output, Escaping & Control Flow

Twig: Output, Escaping & Control Flow

Twig is a templating engine for PHP, most commonly associated with Symfony (usable standalone in any PHP project). It separates presentation/HTML markup from application logic, similar in spirit to Blade for Laravel or Jinja for Python.

Variable Output & Auto-Escaping

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

{# Auto-escaped by default -- prevents XSS. If `comment` contains
   <script>alert('xss')</script>, it renders as harmless literal text #}
<p>{{ comment }}</p>

{# raw filter deliberately opts OUT of escaping -- only for genuinely
   trusted, already-sanitized content #}
<div>{{ articleBody|raw }}</div>

Filters

{{ name|upper }}
{{ name|upper|trim }}       {# chained, applied left to right #}
{{ user.nickname|default('Anonymous') }}  {# fallback for undefined/empty #}

Conditionals & Loops

{% if user.isLoggedIn %}
  <p>Welcome back, {{ user.name }}!</p>
{% else %}
  <p>Please log in.</p>
{% endif %}

{% for product in products %}
  <li>{{ loop.index }}. {{ product.name }} - {{ product.price }}</li>
{% endfor %}

Flexible Dot Notation

{{ user.name }} transparently tries public property access, then getName(), then isName()/hasName() -- the template author doesn't need to know whether the underlying PHP class exposes data as a property or a getter method.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free