Prev |  | Next

# First example

To get a first impression of PHPTAL usage, a simple example is better than many words.

Your template is a valid XML/ HTML document (with a root element). Here's a file named ' `my_template_file.xhtml`'.

            <?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="person people"><td tal:content="person/name">person's name</td><td tal:content="person/phone">person's 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>

In PHP, you just have to include the PHPTAL library, and maybe configure a few variables to customize the template system.

            <?php
    // create a new template object
    $template = new PhpTal\PHPTAL('my_template_file.xhtml');

    // the Person class
    class Person {
        public $name;
        public $phone;

        function Person($name, $phone) {
            $this->name = $name;
            $this->phone = $phone;
        }
    }

    // let's create an array of objects for test purpose
    $people = array();
    $people[] = new Person("foo", "01-344-121-021");
    $people[] = new Person("bar", "05-999-165-541");
    $people[] = new Person("baz", "01-389-321-024");
    $people[] = new Person("quz", "05-321-378-654");

    // put some data into the template context
    $template->title = 'The title value';
    $template->people = $people;

    // execute the template
    try {
        echo $template->execute();
    }
    catch (Exception $e){
        echo $e;
    }
    ?>

If you execute the PHP script, you will obtain something similar to what follows.

            <?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>quz</td><td>05-321-378-654</td></tr></tbody></table></body></html>

PHPTAL doesn't care much about line breaks and indentation in files it reads and generates. If you want source code of generated HTML files to be pretty (with line breaks and perfect indentation), then you might need to postprocess it with HTML Tidy.

Prev |  | Next
Installation | Home | Template Attribute Language