Skip to content
Tutorials Center
My learning

Topics

Lesson 85 of 147 ยท PHP and the Web

Templating: Twig and Blade Concepts

Understand how Twig and Blade work: automatic escaping, filters, loops, layouts and compiled templates, then build a small template engine in PHP yourself.

PHP began life as a templating language: you mixed HTML with <?php ... ?> tags and it simply worked. That is still fine for small pages, as you saw in PHP and HTML. On a larger site, though, plain PHP templates have problems. Authors must remember to call htmlspecialchars() on every single value. Business logic creeps into the markup. Designers face the full power (and danger) of PHP when all they want is to print a name.

Template engines such as Twig (used by Symfony) and Blade (used by Laravel) solve this with a small language of their own. They escape output by default, give you tidy syntax for loops, conditions and layouts, and keep templates focused on presentation. This lesson explains the concepts both share and then builds a miniature engine so nothing about them stays magic.

What a template engine gives you

Compare the same snippet in three flavors:

PHP
<!-- Plain PHP -->
<h1><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?></h1>
<?php foreach ($items as $item): ?>
  <li><?= htmlspecialchars($item['name'], ENT_QUOTES, 'UTF-8') ?></li>
<?php endforeach; ?>
TWIG
{# Twig #}
<h1>{{ title }}</h1>
{% for item in items %}
  <li>{{ item.name }}</li>
{% endfor %}
BLADE
{{-- Blade --}}
<h1>{{ $title }}</h1>
@foreach ($items as $item)
  <li>{{ $item['name'] }}</li>
@endforeach

Both engines escape {{ ... }} automatically. The key ideas they have in common:

Concept Twig Blade
Print an escaped value {{ name }} {{ $name }}
Print raw HTML (dangerous) {{ html|raw }} {!! $html !!}
Comment {# note #} {{-- note --}}
Condition {% if user %}โ€ฆ{% endif %} @if ($user) โ€ฆ @endif
Loop {% for x in xs %} @foreach ($xs as $x)
Inherit a layout {% extends "base.twig" %} @extends('base')
Define / fill a region {% block content %} @section('content') / @yield('content')
Include a partial {% include "card.twig" %} @include('card')
Transform a value {{ name|upper }} PHP functions: {{ strtoupper($name) }}

Escaping is the headline feature

Most cross-site scripting (XSS) bugs come from one forgotten htmlspecialchars(). A template engine flips the default: everything is escaped unless you explicitly ask otherwise. That is safe by default, and unsafe output becomes visible in code review because it needs a special marker (|raw or {!! !!}). The mechanics are the same you learned in XSS and Output Escaping:

PHP Escape by default, raw by choice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The user-controlled name is neutralized, while bio stays as markup because the template author chose {!! !!}. Only use raw output for HTML that you generated or that has been sanitized by a dedicated library.

Real engines go one step further: they are context-aware. Twig can escape differently for HTML, JavaScript, URLs and CSS ({{ value|escape('js') }}), because the right escaping depends on where the value lands. Plain htmlspecialchars() is correct for HTML text and quoted attributes, and wrong for the middle of a <script> block.

Filters, conditions and loops

Twig adds filters: small functions applied with a pipe, {{ name|upper|trim }}. Both engines provide if/else and loops, plus conveniences such as the loop variable (loop.index, loop.first) in Twig and $loop in Blade.

Let's write the parser for those constructs. A template is turned into a tree of nodes (text, variable, if, for), and rendering walks the tree with a data array. This two-step design, parse once, render many times, is how every serious engine works:

flowchart LR
  A["Template source"] --> B["Tokenizer:<br/>text and tags"]
  B --> C["Parser:<br/>tree of nodes"]
  C --> D["Renderer + data"]
  D --> E["HTML output"]

The template is parsed into a tree; only the final step needs the data.

PHP A mini engine: variables, filters, if and for

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The whole engine is about 100 lines, yet it already shows the pieces: a tokenizer that splits text from tags, a recursive parser that handles nesting, dotted-path lookups and an output step that escapes by default. Notice that Ink & Paper came out as Ink &amp; Paper and the <admin> in the user name was escaped too.

Two lessons from the design. First, a template can only reach data you pass in, which keeps it from calling arbitrary code (Twig even has a sandbox mode for untrusted templates). Second, lookups fail softly: a missing key becomes null and prints nothing. Twig and Blade offer strict modes that throw for undefined variables, which is better during development.

Layouts and inheritance

Nearly every site repeats the same frame: header, navigation, footer. Two techniques avoid repetition:

  • Includes paste a partial (a card, a menu) into a page.
  • Inheritance defines a base layout with named blocks; each page extends the layout and fills the blocks.
flowchart TD
  L["base layout<br/>header, block title, block content, footer"]
  P1["home page<br/>extends base"]
  P2["contact page<br/>extends base"]
  P1 -->|"fills title, content"| L
  P2 -->|"fills title, content"| L

Child templates fill named blocks in a shared layout instead of copying the frame.

Inheritance is easy to implement: render the child to find its blocks, then substitute them into the parent. This version handles the common case of one level of inheritance without nested blocks:

PHP Layout inheritance with blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The contact page does not define a title block, so it keeps the parent's default, Untitled. In Twig you call {{ parent() }} to include the parent's block content, and in Blade @parent does the same.

Compiled templates and caching

The mini engine parses on every render. Twig and Blade avoid that cost by compiling each template to a plain PHP file once, then caching it. The next request just runs ordinary PHP, which OPcache keeps in memory. A Blade template like this:

BLADE
<h1>{{ $title }}</h1>
@foreach ($items as $item)
  <li>{{ $item }}</li>
@endforeach

is compiled to roughly this:

PHP
<h1><?php echo e($title); ?></h1>
<?php foreach ($items as $item): ?>
  <li><?php echo e($item); ?></li>
<?php endforeach; ?>

That is why template engines add almost no overhead in production: the translation happens at deploy time or on the first request. When a source file changes, the engine notices (by comparing file times) and recompiles.

Twig, Blade or plain PHP?

  • Blade is part of Laravel. Its syntax is a thin layer over PHP, so you can still write @php ... @endphp and use any PHP expression.
  • Twig is a separate language, stricter and sandboxable. Use it with Symfony or standalone via Composer (twig/twig). It is a good fit when designers who don't know PHP edit templates.
  • Plain PHP templates remain a valid choice for small projects, if you build an e() helper and use it every time.

Whichever you choose, keep logic out of templates: compute data in controllers or view models, then loop and print in the template. If a template needs a complicated if, write a method and call it.

See also Design Patterns for the MVC idea that templates plug into, and Frameworks for how real projects wire them up.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does it mean that Twig and Blade escape output "by default"?

    The safe behavior is the default, and unsafe output needs a deliberate marker such as |raw or {!! !!}.
  2. 2. In the mini engine, why is the template parsed into a tree before rendering?

    Parsing is the expensive, data-independent step. A tree can be reused for each render with new data.
  3. 3. Which statement about layout inheritance is correct?

    The parent declares blocks as extension points and the child supplies their content, so the shared frame lives in one file.
  4. 4. Why do Twig and Blade compile templates to PHP?

    Compilation happens once per template change; afterwards the cached PHP file runs like any other script.
  5. 5. Where is htmlspecialchars()-style escaping the WRONG choice?

    JavaScript contexts need JavaScript escaping (for example json_encode or Twig's escape('js')). HTML escaping alone does not make that safe.

Summary

  • Template engines such as Twig and Blade give you a small, presentation-focused language with automatic output escaping.
  • Raw output (|raw, {!! !!}) is an explicit, reviewable exception, and the correct escaping depends on context (HTML, attribute, JavaScript, URL).
  • Engines tokenize and parse templates into a tree (or compiled PHP), then render it with data.
  • Layouts use inheritance: a base template defines blocks and child templates fill them; includes reuse partials.
  • Compiled, cached templates make engines nearly as fast as plain PHP.
  • Keep logic in controllers and models, and keep templates for presentation.

Next: PHP and Databases