Skip to content

ch05_templating

Daniel Samson edited this page Oct 15, 2019 · 20 revisions

TeensyPHP also provides the template method to render templates, components, or mix-ins. Templates are written in PHP.

template(string $path, array $variables)

Example Template

//homepage.php
<h1>Welcome Home <?= $username ?></h1>

Use template in the router

// index.php
route(method(GET), url_path("/"), function() {
    render(200, html_out(template('homepage.php', ['username' => $_SESSION['username']));
});

Components / Mixins

Sometimes it might make sense to make some smaller templates so that you can reuse them in other templates. We can simply reuse the template function to achieve this.

Let's create a component to keep all the css imports:

// components/css.php
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Now we can create a component for the head element of all pages, so that do not need to edit the head in each page:

// components/page_header.php
<!DOCTYPE html>
<html>
<head>
<title>My site - <?= $title ?></title>
<?= template(__DIR__.'/css.php', []) ?>
</head>
<body>

Just to keep things sane, lets also add a footer as well:

// components/page_footer.php
</body>
</html>

Now we can create our main templates with less mark up and we can ensure that we only need to edit the head element once:

// homepage.php
<?= template(__DIR__.'/components/page_header.php', ['title' => 'Welcome Home']) ?>
<h1>Hello World</h1>
<?= template(__DIR__.'/components/page_footer.php', []) ?>

We can use the template function in the router:

route(method(GET), url_path("/"), function() {
    render(200, html_out(template('homepage.php', []));
});

Templating other file types

The template function is not just limited to html. The file type is controlled by the content function (see controlling actions for details)

Lets create a template for json errors

<?php // components/json_error.php ?>
{
  "errors": {
    "code": <?= json_encode($code) ?>,
    "title": <?= json_encode($message) ?>
  }
}

Now we render them when an exception is thrown:

try {
    // something
} catch (Exception $e) {
    render(500, content(JSON_CONTENT, template(__DIR__.'/components/json_error.php', ['code' => $e->getCode(), 'message' => $e->getMessage()]));
}