Views-functions are responsible to return the html-code of the requested page. The common "hello world" example would look like this:
<?php function view($request_info) { return "hello world"; } ?>
In practice a complete page starting with the document-type header will be returned, containing the dynamic parts. So PHP is not embedded into HTML as usual, but HTML is embedded into PHP. However, both ways are bad programming style because of mixing presentation- and program-logic. To avoid this, tk_self is designed to use templates to render the html-code.
To write a new view-function and to use a template engine create a file with the following PHP-code and save this file i.e. as test.php in the /views directory:
<?php function view($request_info) { $context = array("message" => "this is the test-page"); $engines = array( "PHP" => "www.php.net", "Smarty" => "www.smarty.net", "PHPTAL" => "phptal.motion-twin.com", ); $context["engines"] = $engines; render_to_response("test.tpl", $context); } ?>
Every view-function gets one argument: $request_info. This is an assoziative array with the following elements:
| Table: view-function parameters | |
|---|---|
| "pattern" | The pattern used to bind the URL to the view-function |
| "uri" | The URL thats points to this view |
| "args" | An assoziative array storing name-captured parameters extracted from the URL |
These arguments are explained in detail in URL-mapping.
The function render_to_response() is implemented by tk_self and invokes the template-engine defined in the tk_settings.php file. This function gets two parameters: the filename of the template to use and the data to render as the context, which is an assoziative array.
The second argument $context is optional if there is no content to render, but this is the same as delivering a static file. That may make sense under some special circumstances, but static files should be served from the htdocs/static directory (or a subdirectory therein), so that tk_self (and PHP) is not invoked at all.
The template file test.tpl must be stored in a template engine dependent directory. How to create the templates for view-functions and where to store them are described in the Templates-chapter.