PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Eight Weeks of Prototype: Week 7, Other Prototype Functionality

The Template Class

The Template class allows you to create a block of text (be it HTML, plaintext or otherwise) in which there are placeholders. You can then evaluate the template to substitute a set of values in for the placeholders. This is useful for doing things such as defining how data retrieved from Ajax request should be displayed.

A placeholder is denoted in a template by using #{variable name}. For instance, if you wanted to substitute in a variable called country you would use #{country}. The string containing the placeholders is passed to the constructor of the Template class, as shown in Listing 1.

Listing 1 Invoking the Template class (listing-1.js)
var tpl = new Template('#{name} is from #{country}');

In order to retrieve the evaluated template with the actual values instead of the placeholders, you call the evaluate() method on the tpl variable. This method accepts a single argument, which is an object (or Hash, as shown in the third article of this series) containing key / value pairs for each placeholder.

The evaluated template is returned from the call to evaluate(), which you can then use as required. If a corresponding value isn't found for a given placeholder, an empty string is used. Listing 2 shows an example of defining data to be used when evaluating a template. The resultant string is used to populate the #foo div.

Listing 2 Basic usage of the Template class (listing-2.html)
<html>
    <head>
        <title>Basic usage of the Template class</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div id="foo"></div>
 
        <script type="text/javascript">
 
            var tpl = new Template('#{name} is from #{country}');
 
            var person = {
                name : 'Quentin',
                country : 'Australia'
            };
 
            $('foo').update(tpl.evaluate(person));
        </script>
    </body>
</html>

As mentioned above, the Template class is useful for handling data from an Ajax request. In the next example we will retrieve some JSON data (just as we have done in the previous two articles in this series), and display the returned data with the help of a template.

Listing 3 shows how we can return JSON data from PHP. This code is the same as is used in the previous two articles. For a full explanation refer to fifth article in this series.

Listing 3 Using PHP to send JSON data (listing-3.php)
<?php
    $person = array(
        'name'    => 'Quentin',
        'country' => 'Australia'
    );
 
    header('Content-type: application/json');
 
    echo json_encode($person);
?>

Now we can create the JavaScript code that makes use of this JSON data. In Listing 4, I have created a class called PersonLoader which retrieves the data from Listing 3 using Ajax, then feeds the returned values into a template created using the Template class. For more details about Ajax requests and how classes work with Prototype, please read the previous two examples in this series.

Listing 4 Combining an Ajax request with the Template class (listing-4.html)
<html>
    <head>
        <title>Combining an Ajax request with the Template class</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div id="foo"></div>
 
        <script type="text/javascript">
            var PersonLoader = Class.create({
 
                initialize : function(container)
                {
                    this.container = $(container);
 
                    var options = {
                        onSuccess : this._loadSuccess.bind(this)
                    };
 
                    new Ajax.Request('listing-03.php', options);
                },
 
                _loadSuccess : function(transport)
                {
                    var tpl = new Template('<strong>#{name}</strong> is from <em>#{country}</em>');
                    var content = tpl.evaluate(transport.responseJSON);
 
                    this.container.update(content);
                }
            });
 
            new PersonLoader('foo');
        </script>
    </body>
</html>

You may notice in this example that HTML tags are used in the template. Since you can use any text that you like, the use of the Template class can be quite powerful.

In This Article