EthicsComputerCourses
Join training +91 90532 10052

PHP Templates & Layouts

LAMP Stack · Lesson 10 of 20 Intermediate 12 min read Updated

By the end of this lesson ShikshaPortal's pages will be built from plain PHP templates in a tidy way. Each template will run in its own scope, a whole page will be built in memory before anything is sent, one layout will wrap every page, small partials will remove repeated markup, and you will know exactly how to escape a value in text, in an attribute, in a URL and in JavaScript.

What you should know first: include & require and Form Validation & Escaping from the PHP course, and the controllers and templates/ folders from Organising Code: A Simple MVC.

PHP is already a template language

PHP was born for mixing HTML with small bits of code, so it needs no separate template engine. A template is a file that is mostly HTML with a few holes for data. Two pieces of syntax keep templates readable:

  • <?= e($value) ?> is the short echo tag. It means <?php echo e($value); ?> and is always available.
  • <?php if (...): ?> ... <?php endif; ?> and foreach (...): ... endforeach; are the alternative syntax. The named endings are easier to match with HTML than a lonely }.

Think of a pre-printed report card. The school prints the frame once: logo, table lines, signature boxes. A clerk only fills in the blanks. The clerk never calculates a percentage on the card; that was done in the office. Templates work the same way: they print, loop and choose, but they never run SQL or make business decisions. The controller hands them finished data.

Step 1: two problems with the old render()

Since the Apache lesson, render() has done this:

PHP
function render(string $template, array $data = []): void
{
    extract($data, EXTR_SKIP);
    require APP_ROOT . '/templates/layout.php'; // the layout then requires the page template
}

It is short, but it has two real problems, and we hit both while building this course.

Shared variables. The layout and the page template run in the same scope, so a variable in one can overwrite a variable in the other. In the login lesson, our first layout looped over flash messages with foreach (take_flashes() as $message). The error page also uses $message. A teacher who opened an admin-only page saw "Welcome, Vikram Yadav." where "Your account cannot do this." should have been. The fix then was to rename the loop variable; the real fix is separate scopes.

Half-sent pages. The layout starts printing straight away. If something fails halfway through a template, the first half is already on its way to the browser, and then the error page is printed after it. We made a template run a query with a typing mistake in the table name and requested /classes. Here is the middle of the real response:

Output
        </table>
        <p>Rooms in use: <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Something went wrong | ShikshaPortal</title>

One response, two <!DOCTYPE html> lines, and a page that says "Classes" at the top and "Something went wrong" further down. It also shows why templates should not run queries.

Step 2: build the page in memory with view()

PHP's output buffering catches everything that would be printed and holds it in memory. ob_start() starts catching, and ob_get_clean() returns the caught text and stops. The new view() in src/helpers.php uses it, and render() is rebuilt on top:

PHP
/**
 * Run one template with its own variables and return the HTML as a string.
 * Nothing reaches the browser until the whole template has finished.
 */
function view(string $template, array $data = []): string
{
    if (!preg_match('#^[a-z0-9_/-]+$#', $template)) {
        throw new InvalidArgumentException("Bad template name: {$template}");
    }
    extract($data, EXTR_SKIP);
    ob_start();
    try {
        require APP_ROOT . '/templates/' . $template . '.php';
        return (string) ob_get_clean();
    } catch (Throwable $e) {
        ob_end_clean(); // throw away the half-built page
        throw $e;
    }
}

/** Build the page, wrap it in the layout, and send it. */
function render(string $template, array $data = []): void
{
    $content = view($template, $data);
    echo view('layout', [
        'title' => $data['title'] ?? 'ShikshaPortal',
        'content' => $content,
        'user' => current_user(),
        'flashes' => take_flashes(),
    ]);
}

What each part buys you:

  • Separate scopes. Each view() call is a new function call, so a template sees only the variables in its own $data (plus $template and $data themselves). The layout cannot overwrite the page's $message.
  • All or nothing. The page template runs completely before the layout starts. If it throws, ob_end_clean() discards the partial HTML and the error travels up to the try/catch in public/index.php, which renders a clean error page.
  • A safe template name. The pattern allows only lowercase letters, digits, _, - and /. A name like ../.env can never be built, even if a future bug passes user input to view(). Our test: view('../.env') threw "Bad template name: ../.env".
  • Controllers do not change. They still call render('students/index', [...]).

The same broken template now gives one clean page. The real response, shortened:

Output
HTTP/1.1 500 Internal Server Error
...
    <title>Something went wrong | ShikshaPortal</title>
...
        <h1>Something went wrong</h1>

The whole response contained exactly one <!DOCTYPE html>.

Step 3: one layout for every page

templates/layout.php now receives $title, $content, $user and $flashes, and calls no functions that touch the session or database:

PHP
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= e($title) ?> | ShikshaPortal</title>
    <link rel="stylesheet" href="/assets/css/app.css">
</head>
<body>
<?= view('partials/header', ['user' => $user]) ?>
    <main>
<?php foreach ($flashes as $flash): ?>
        <p class="flash" role="status"><?= e($flash) ?></p>
<?php endforeach; ?>
<?= $content /* already-escaped HTML from view() */ ?>
    </main>
    <footer>ShikshaPortal, Lucknow</footer>
</body>
</html>

Look at the two lines without e(). $content and the header partial are HTML that our own templates built, with every value inside already escaped. Escaping them again would show visitors &lt;h1&gt; instead of a heading. These are the only unescaped echoes in the app, and the comment says why. Any other <?= without e() in a review is a bug until proven otherwise.

Step 4: partials for repeated markup

A partial is a small template used inside other templates. The header moves to templates/partials/header.php, and it now marks the menu link for the current page:

PHP
    <header>
        <a href="/" class="logo">ShikshaPortal</a>
        <nav aria-label="Main">
<?php foreach (['/classes' => 'Classes', '/students' => 'Students', '/about' => 'About'] as $href => $label): ?>
            <a href="<?= e($href) ?>"<?= is_current($href) ? ' aria-current="page"' : '' ?>><?= e($label) ?></a>
<?php endforeach; ?>
        </nav>
<?php if ($user !== null): ?>
        <form method="post" action="/logout" class="user">
            <?= e($user['name']) ?> (<?= e($user['role']) ?>) <button>Log out</button>
        </form>
<?php else: ?>
        <a href="/login" class="user">Log in</a>
<?php endif; ?>
    </header>

is_current() is a tiny helper in src/helpers.php that compares a path with the request's path. aria-current="page" tells screen readers "you are here", and CSS can style it with nav [aria-current="page"] { font-weight: 700; }. On /students?class_id=3, our server sent:

Output
<a href="/classes">Classes</a>
<a href="/students" aria-current="page">Students</a>
<a href="/about">About</a>

The student form repeated the same label, input and error markup five times. templates/partials/field.php holds it once, and also links the error message to its input for screen readers:

PHP
            <p>
                <label for="<?= e($name) ?>"><?= e($label) ?></label>
                <input id="<?= e($name) ?>" name="<?= e($name) ?>" type="<?= e($type) ?>"
                       value="<?= e($value) ?>" required<?php if ($error !== null): ?> aria-invalid="true" aria-describedby="<?= e($name) ?>-error"<?php endif; ?>>
<?php if ($error !== null): ?>
                <strong class="error" id="<?= e($name) ?>-error"><?= e($error) ?></strong>
<?php endif; ?>
            </p>

templates/students/form.php calls it in a loop:

PHP
<?php foreach ([
    'admission_no' => ['Admission no.', 'text'],
    'full_name' => ['Full name', 'text'],
    'date_of_birth' => ['Date of birth', 'date'],
    'guardian_name' => ['Guardian name', 'text'],
    'guardian_phone' => ['Guardian mobile', 'tel'],
] as $name => [$label, $type]): ?>
<?= view('partials/field', [
    'name' => $name, 'label' => $label, 'type' => $type,
    'value' => $student[$name] ?? '', 'error' => $errors[$name] ?? null,
]) ?>
<?php endforeach; ?>

For a bad admission number, the first field came back as:

Output
<p>
    <label for="admission_no">Admission no.</label>
    <input id="admission_no" name="admission_no" type="text"
           value="SP-26-35" required aria-invalid="true" aria-describedby="admission_no-error">
    <strong class="error" id="admission_no-error">Use the format SP-2026-0042.</strong>
</p>

A partial receives only what you pass it. That makes it easy to reuse and impossible to break by accident from the outside.

Step 5: escape for the context

e() is right for HTML text and for attribute values inside quotes. Other places need other tools:

Where the value goesUseExample
HTML texte()<td><?= e($s['full_name']) ?></td>
Attribute valuee(), always inside double quotesvalue="<?= e($name) ?>"
URL query stringurl() (built on http_build_query()), then e()href="<?= e(url('/student', ['id' => $id])) ?>"
Inside <script>json_encode() with the JSON_HEX_* flagsconst data = <?= json_encode($data, $flags) ?>;

The new url() helper encodes query values. Our test with a search for Ram & Shyam:

PHP
echo url('/students', ['class_id' => 3, 'q' => 'Ram & Shyam']), "\n";
echo e(url('/students', ['class_id' => 3, 'q' => 'Ram & Shyam'])), "\n";

$name = '</script><script>alert("hi")</script>';
echo json_encode(['name' => $name], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_THROW_ON_ERROR), "\n";
Output
/students?class_id=3&q=Ram+%26+Shyam
/students?class_id=3&amp;q=Ram+%26+Shyam
{"name":"\u003C\/script\u003E\u003Cscript\u003Ealert(\u0022hi\u0022)\u003C\/script\u003E"}

Without url(), the & in the name would start a new parameter and the search would break. e() then turns the separator & into &amp;, which is correct inside an HTML attribute. In the JSON, JSON_HEX_TAG turns < and > into \u003C and \u003E, so a name can never close the <script> element, and the other flags do the same for & and both kinds of quotes. JavaScript reads those codes back as the original characters. This matters again when PHP hands data to JavaScript in AJAX with fetch and JSON APIs.

Why "always inside double quotes"? e() escapes <, >, & and quotes, but not spaces or =. In an unquoted attribute, a space ends the value, and the rest becomes new attributes. Run this page to see the difference. The same value is printed twice, once quoted and once not:

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Quote your attributes</title>
  <style>body { font-family: system-ui, sans-serif; margin: 16px; } pre { background: #f4f4f4; padding: 8px; }</style>
</head>
<body>
  <h1>Guardian: Ram onmouseover=this.dataset.hacked=1</h1>
  <p><a id="quoted" href="#" title="Ram onmouseover=this.dataset.hacked=1">Quoted title</a></p>
  <p><a id="unquoted" href="#" title=Ram onmouseover=this.dataset.hacked=1>Unquoted title</a></p>
  <pre id="out"></pre>
  <script>
    const lines = [];
    for (const id of ["quoted", "unquoted"]) {
      const link = document.getElementById(id);
      const names = [...link.attributes].map((a) => a.name).join(", ");
      lines.push(id + ": attributes = " + names);
      lines.push("  title = " + JSON.stringify(link.getAttribute("title")));
    }
    document.querySelector("#out").textContent = lines.join("\n");
  </script>
</body>
</html>

The quoted link has a harmless title. The unquoted one gained an onmouseover attribute: a script that runs when someone moves the mouse over it. The value contained no <, > or quotes, so e() would not have changed it. Quotes are part of the escaping.

Step 6: hand templates their data

Templates should not reach out for data. The student list shows "Add a student" only to admins, so the controller now passes the user in, and the template only decides:

PHP
<?php if ($user['role'] === 'admin'): ?>
        <p><a href="/students/new">Add a student</a></p>
<?php endif; ?>
<?php if ($students === []): ?>
        <p>No students match. <a href="/students">Show all students</a></p>
<?php else: ?>
        <table>
            ...
<?php endif; ?>

StudentController::index() and show() add 'user' => $user (the value require_login() returns) to their data. Hiding the button is only for tidiness. The real protection is still require_login('admin') in the controller, because anyone can send the POST request directly.

Common mistakes

  • Echoing without e(). Every value from a person or the database is untrusted. Escape by default.
  • Unquoted attributes. Spaces in the value create new attributes. Always use double quotes.
  • Building query strings by joining text. &, # and spaces break them. Use url().
  • Running SQL in a template. A failure there leaves half a page, and the logic is hard to find. Pass data from the controller.
  • Passing request input to view() as a template name. That invites path traversal. Template names come from your code only.

Interview questions

1. Why use output buffering when rendering templates?

Buffering lets the server build the whole page in memory before sending anything. If an error happens midway, the partial output is discarded and a clean error page with the right status code is sent. It also lets a template's output be passed around as a string, for example into a layout.

2. What does "context-aware escaping" mean?

The correct escaping depends on where the value is placed. HTML text and quoted attributes need HTML entity escaping, URL parameters need URL encoding, and values inside JavaScript need JSON encoding with HTML-sensitive characters escaped. Using HTML escaping in the wrong context can still allow injection.

3. Why is it a problem when a layout and page template share one scope?

Variables leak between them, so a loop variable or helper value in one file can silently overwrite data the other file needs. Rendering each template inside its own function call gives each one only the variables passed to it.

4. What is a partial, and what should it receive?

A partial is a small reusable template, such as a header or a form field. It should receive only the values it needs as explicit parameters, which makes it predictable and easy to reuse on any page.

Key points

  • PHP templates print, loop and choose; controllers prepare all the data.
  • view() runs a template in its own scope with output buffering and returns a string.
  • render() builds the page first, then the layout, so errors never produce half pages.
  • The layout's $content is the one deliberate unescaped echo; everything else goes through e().
  • Partials such as partials/header and partials/field remove repeated markup and receive explicit data.
  • Escape by context: e() with double quotes for HTML, url() for query strings, json_encode() with JSON_HEX_* flags for scripts.

Exercise

The class drop-down list appears in two places: the filter on templates/students/index.php and the form in templates/students/form.php. Move it into templates/partials/class-select.php, which receives name, classes, selected (an id or null) and placeholder (text for an empty first option, or null for none). Use it in both templates, and make sure every value is escaped.

Show solution
PHP
<select id="<?= e($name) ?>" name="<?= e($name) ?>"<?= $placeholder === null ? ' required' : '' ?>>
<?php if ($placeholder !== null): ?>
    <option value=""><?= e($placeholder) ?></option>
<?php endif; ?>
<?php foreach ($classes as $id => $label): ?>
    <option value="<?= e($id) ?>"<?= $id === $selected ? ' selected' : '' ?>><?= e($label) ?></option>
<?php endforeach; ?>
</select>
PHP
<!-- students/index.php -->
<label>Class
    <?= view('partials/class-select', ['name' => 'class_id', 'classes' => $classes,
        'selected' => $classId, 'placeholder' => 'All classes']) ?>
</label>

<!-- students/form.php -->
<label for="class_id">Class</label>
<?= view('partials/class-select', ['name' => 'class_id', 'classes' => $classes,
    'selected' => (int) ($student['class_id'] ?? 0), 'placeholder' => null]) ?>

The partial gets all four values explicitly, so it cannot depend on variables that happen to exist in the calling template. Both callers keep their own label, because the filter wraps the select in its label while the form uses for.

Quick Quiz

1. What does ob_get_clean() do inside view()?

2. Which echo in the layout is allowed without e()?

3. A guardian name is printed as title=<?= e($name) ?> without quotes. Why is that unsafe?

4. How should a search term be added to a link's query string?

Learn LAMP Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call