Server-Side Templates

There are two types of templates within the framework.

  • Master Templates - These are reusable html/php file that provides an easy way to change the look and feel of a web page or application.
  • HTML Templates - A set of matched elements or snippets of html codes that contains template fields that are parsed and rendered when binded to a dataset.

Master Templates

A master template contains the basic html structure needed for rendering the layput of a page. Before you can use a master template you need to identify the content area of the template by assigning the "master-content" css class name to an element within the template.

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>My Website</title>

        <h2>My Website</h2>
        <div class="master-content">
            <!-- your content will be loaded here -->


To set or change the template of a web page,you will need to set the "$masterTemplate" page property as shown below:



    class NewPage extends RaxanWebPage {

        protected function _config() { // config handler
            $this->masterTemplate = 'path/to/master.html'; // works with .php and .html files

        protected function _load() {
            // append the content.html view

            // or just set the content of the page to hello world
            // $this->content('Hello World');



The "masterTemplate" property will load either a ".html" or ".php" file. If you're using a ".php" file there might be times when you would want to prevent the file from being access directly. To do this simply add the following line of code the to top of the master template page:

<?php defined("RAXANPDI") || die("Access Denied"); ?>

In addition to setting the $masterTemplate property of the page, you can also set the $masterContentBlock property to use your own template content css selector. The default template content selector is ".master-content".

    protected function _config() { // config handler
        $this->masterTemplate = 'path/to/master.html';
        $this->$masterContentBlock = '#page-content';  // set master content block selector

HTML Templates

The template binder API is used to parse and render html templates within the page. Each template is parsed and the template fields replaced with content from a dataset. The rendered html is either inserted into matched element.

The bind() method is used to bind a set of array elements or objects to the template's child elements or text content. It acts as a wrapper to Raxan::bindTemplate() and supports binding to a list of values from an Array, PDO recordset or a set of DOM elements as shown below:

    protected function _load() {
        // create new array
        $urls = array();
        $urls[] = array('name'=>'PHP Website', 'link'=>'');
        $urls[] = array('name'=>'Yahoo', 'link'=>'');
        $urls[] = array('name'=>'Google', 'link'=>'');

        // bind array to the #list element

        // bind to data from a database
        $db = $this->Raxan->connect('my-database');
        $dataset = $db->table('customers');

        // bind to attributes from .person elements within the page
        $person = $this['.person'];

Here's the html markup for the list1 element:

    <ul id="list">
        <li><a href="{link}">{name}</a></li>

In the above, {link} and {name} are template fields that will be replaced with values from the "$urls" array.

Note: By default the framework will encode special HTML/XML characters (e.g. <,>) within an unformatted template field. Use the format option to set the type of formatting to be applied to the field.

Built-in Template fields

  • INDEX - Represents the current index of an indexed array
  • VALUE - Represents value from an indexed array
  • ROWCLASS - Represents the CSS class value. See the CSS class name options
  • ROWCOUNT - Represents the row number being rendered

        <li id="item-{ROWCOUNT}" class="{ROWCLASS} country">{name}</li>

The {INDEX} and {VALUE} fields are only available when working with indexed arrays.

Template binder syntax:

  • $data - Array of elements or objects to bind to the template.
  • $options - Optional. An array of templates bind options. For example array($mainTemplate, $alternateTemplate). As of version 1.0 Beta 1 additional options can be passed as an associative array. Eg. array('tpl'=> $mainTemplate, 'tplAlt'=> $alternateTemplate)

Template binder Option values:

Template options

  • tpl - Main template
  • tplAlt - Alternate template
  • tplFirst - First template
  • tplLast - Last template
  • tplSelected - Selected template
  • tplEdit - Edit template

Use the above template options to manually set the html templates for the matched element(s). If template options were not specified then the inner html for the matched elements will be used as the main template.

    protected function _load() {
        // code to get data here
        $this->customers->bind($data, array(
            'tpl' => '{first_name} {last_name}',
            'tplAlt' => '<div class="bold">{first_name} {last_name}</div>'

CSS class name options

  • itemClass - Item class
  • altClass - Alternate item class
  • selectClass - Selected item class
  • editClass - Edited item class
  • firstClass - First item class
  • lastClass - Last item class

The css class name options are used to set the {ROWCLASS} template field for the row being rendered

    protected function _load() {
        // code to get data here
        $this->orderItems->bind($data, array(
            'itemClass' => 'white-row',
            'altClass' => 'silver-row'

Sample template:
<div id="orderItems">
    <div class="{ROWCLASS} item">{code} {desc} {qty}</div>

Page/Pager options

  • page - Currently selected page
  • pageSize - Size the current page
  • truncString - String to use when truncating a records
  • truncate - Truncate rows. Format: NumberOfRowsToTruncate.Offset. For example, 1.0 will truncate the first row. A negative value of -1.0 will truncate the last row, while a value of 2.1 will truncate the first 2 rows (row 2 to 3) after row 1.

Format option

  • format - Array contain field names and datatypes.

Format data types ("name" => type):

  • integer Convert to integer
  • float - Convert to float
  • money - Convert to money
  • number:decimal - Convert to number with optional decimal values. For example: number:2
  • date:format - Convert to date values using PHP date() format. For example, date:Y-m-d
  • escape - Escape html special characters
  • capitalize - Capitalize words
  • replace:searchRegex,replacedValue - replace regex pattern with value. For example: replace:blue,green
  • upper - Converts text to upper-case characters
  • lower - Convert to lower-case characters
  • html - Allow special html tags. Remove script and style tags
  • raw - Allow raw text

Format options are used to format or filter data values

    protected function _load() {
        // code to get data here
        $this->taskList->bind($data, array(
            'format' => array(
                'title' => 'capitalize',
                'due_date' => 'date:Y-m-d',
                'duration' => 'integer'

Format styles ("name style" => value):

  • bold - Bold text
  • color - Color text
  • style - Inline css style

Use the style options to style text values

    protected function _load() {
        // code to get data here
        $this->taskList->bind($data, array(
            'format' => array(
                'title style' => 'text-decoration:underline',
                'due_date bold' => true,
                'duration color' => 'blue'

The style options can be very useful when rendering values via a callback function:

    protected function _load() {
        // code to get data here
            'callback' => array($this,'rowHandler'),

    // param $tplType = Raxan::TPL_* contants
    public function rowHandler(&$row, $index, $tpl, $tplType, &$fmt, $cssClass) {
        $status = $row['status'];
        if ($status=='overdue') $fmt['title color'] =  'red';
        else if ($status=='due') $fmt['title color'] =  'blue';
        else $fmt['title color'] =  'green';
        if ($status=='complete') return false; // skip current row

Other options

  • key - Name of the field to used when selected or editing rows
  • edited - Key value of row to be edited. This will use tplEdit as the active template for the row being edited
  • selected - Selected key values. Multiple values can be passed in as an array
  • returnArray - Return the result as an array. Used when making a direct call to Raxan::bindTemplate()
  • delimiter - Delmiter used to separate each row
  • removeUnusedTags - Set to true to remove unused template tags. Defaults to true
  • initRowCount - Initial Row Count value. Defaults to 1
  • callback - Callback function to render each row. Callback function parameters: (array) $row, (int) $index, (string) $tpl, (int) $tplType , (array) $format, (string) $cssClass

Example of a callback function:

    public function rowHandler(&$row, $index, $tpl, $tplType, &$fmt, &$cssClass) {
        if ($row['status']=='hide') return false; // skip current row
        else if ($row['status']=='show') {
            return '<td colspan="4">'.htmlspecialchars($row['details']).'</td>'; // return rendered row

        // change row class when status == cancelled
        if ($row['status']=='cancelled') $cssClass = 'rax-error-pal';

See also Raxan::bindTemplate()

Up Next: State Management