Manual

Pierwszy przykład

Aby zrozumieć działanie systemu PHPTAL najłatwiej można to zrobić na prostym przykładzie.

Twój szablon jest poprawnym dokumentem XML/HTML (z nadrzędnym elementem). Oto pliku szablonu nazwany my_template_file.html.

<?xml version="1.0"?>
<html>
  <head>
    <title tal:content="title">
      place for the page title
    </title>
  </head>
  <body>
    <h1 tal:content="title">sample title</h1>
    <table>
      <thead>
        <tr>
          <th>name</th>
          <th>phone</th>
        </tr>
      </thead>
      <tbody>
        <tr tal:repeat="item result">
          <td tal:content="item/name">item name</td>
          <td tal:content="item/phone">item phone</td>
        </tr>
        <tr tal:replace="">
          <td>sample name</td>
          <td>sample phone</td>
        </tr>
        <tr tal:replace="">
          <td>sample name</td>
          <td>sample phone</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

W PHP wystarczy dołączyć bibliotekę PHPTAL i wypełnić kilka zmiennych aby skonfigurować system szablonów.

<?php
require_once 'PHPTAL.php';

// tworzymy obiekt nowego szablonu
$template = new PHPTAL('my_template_file.html');

// klasa Person
class Person {
    public $name;
    public $phone;
    
    function Person($name, $phone) {
        $this->name = $name;
        $this->phone = $phone;
    }
}

// tworzymy testowa tablice obiektow
$result = array();
$result[] = new Person("foo", "01-344-121-021");
$result[] = new Person("bar", "05-999-165-541");
$result[] = new Person("baz", "01-389-321-024");
$result[] = new Person("buz", "05-321-378-654");

// dodajmy pewne dane do tresci szablonu
$template->title = 'the title value';
$template->result = $result;

// uruchamiamy i wyswietlamy szablon
try {
    echo $template->execute();
}
catch (Exception $e){
    echo $e;
}
?>

Jeśli uruchomimy skrypt w otrzymamy taki kod:

<?xml version="1.0"?>
<html>
  <head>
    <title>the title value</title>
  </head>
  <body>
    <h1>the title value</h1>
    <table>
      <thead>
        <tr>
          <th>name</th>
          <th>phone</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>foo</td>
          <td>01-344-121-021</td>
        </tr>
        <tr>
          <td>bar</td>
          <td>05-999-165-541</td>
        </tr>
        <tr>
          <td>baz</td>
          <td>01-389-321-024</td>
        </tr>
        <tr>
          <td>buz</td>
          <td>05-321-378-654</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>