A first template

Exercise 1 of 7 in chapter 6 · 150 XP · 3 objectives checked by tests

Topics covered: Template<?= ?>ob_start()extract()require

Madame Lou wants to touch up the “Lost in the post” page, but its HTML is buried in concatenations: '<p><a class="retour" href="' . Url::vers('/') . '">'… A template (gabarit in French) turns things around: it is a file of HTML, with just enough PHP to slip the values in. First you need the tool that fills it in: a Vue (view) class.

Your mission

  1. Write Vue::rendre($gabarit, $variables) (render) in src/Web/Vue.php: it runs the file templates/<gabarit>.php, where each key of $variables has become a variable, and returns the HTML it produces, without displaying it.
  2. Write templates/introuvable.php (not found): the HTML of the “Lost in the post” page (<main class="lecture">, the heading, the apology, the back link), with <?= Url::vers('/') ?> for the address of the front page.
  3. Page::introuvable() takes its content from this template: Vue::rendre('introuvable').

What a template looks like

<?php use Gazette\Web\Url; ?>
<main class="lecture">
    <h2>Lost in the post</h2>
    <p><a class="retour" href="<?= Url::vers('/') ?>">← Back to the front page</a></p>
</main>

<?= … ?> is short for <?php echo …; ?>: it displays a value in the middle of the HTML. Everything outside the PHP tags is displayed as is. The template is a separate file: the use statements of Vue.php do not apply to it, so it declares use Gazette\Web\Url; itself, on its first line.

Reminder

Three tools to write Vue::rendre():

ob_get_clean() can also return false if something goes wrong. (string) in front of a value converts it to a string, just as (int) converts it to an integer: return (string) ob_get_clean(); keeps the promise of the string return type.