Back to top

This is an old revision of the document!


Templates

Every template is an instance of the <php>Template</php> class defined in include/utils.php.

Context

Templates are intitialized with a context object, which is an associative array. The individual elements of this array are made available in the templates as regular variables (see extract). Consider the context

<PHP> $context = [

'title' => 'Home',
'page_id' => 'index'

]; </PHP>

and the template

<PHP> <html>

<head>
  <title><?= $title ?></title>
</head>
<body>
   <h1><?= $title ?></h1>
   page_id: <?= $page_id ?>
</body>

</html> </PHP>

which renders as

<HTML>

<h1>Home</h1>
page_id: index

</HTML>

Template functions

The following functions are available to escape data to prevent XSS attacks.

* <php>html($data)</php> Escapes data to be used as (part of) an HTML element's content. * <php>attr($data)</php> Escapes data to be used as (part of) an HTML element's attributes. * <php>format_plain_text($text)</php> Escapes and wraps paragraphs in <p> elements. * <php>format_code($code)</php> Escapes and wraps code in <pre> elements.

WARNING! No data is escaped by default. Always escape your template variables.

The following snippet shows how these functions should be used.

<PHP> <section>

<h1><?= $this->html($title) ?></h1>
<?= $this->format_plain_text($some_text) ?>
<?= $this->format_code($some_code) ?>
Author <a href="<?= $this->attr($url_to_author_page) ?>"><?= $this->html($author_name) ?></a>

</section> </PHP>

Template inheritance

Rack templates support basic template inheritance, provided by the following functions:

  • <php>Template→extends($template)</php> This function sets the parent template, where <php>$template</php> as a path relative to the current template.
  • <php>Template→begin($block_name)</php> This function begins a new block.
  • <php>Template→end()</php> This function ends a block.

Note that nested blocks are not supported and that blocks are only allowed in templates that extend a parent template.

The following snippets demonstrate the use of blocks and template inheritance.

page.phtml
<?php $this->extends('layout.phtml') ?>
 
<?php $this->begin('content') ?>
Hello world!
<?php $this->end() ?>
layout.phtml
<html>
  <head>
    <title><?= $title ?></title>
  </head>
  <body>
   <?= $content ?>
  </body>
</html>

More functionality

These templates are parsed and executed as PHP and therefore can execute arbitrary PHP code. However, it is advised to keep it simple in order to maintain separation between rendering and internal logic.

By convention, templates use the Alternative syntax for PHP control structures. Definitions of non-anonymous functions in templates are forbidden (by design) and anonymous functions should only be used in templates in exceptional situations.


documentation/rack/reference/templates.1527271737.txt.gz · Last modified: 2022/04/03 16:00 (external edit)