Class: SimpleTemplate

  • Package: saf.Template
  • Author: John Luxford <lux@simian.ca>
  • Copyright: Copyright (C) 2001-2003, Simian Systems Inc.
  • License: http://www.sitellite.org/index/license Simian Open Software License
  • Version: 2.4, 2004-01-07, $Id: Simple.php,v 1.9 2008/03/09 18:46:06 lux Exp $
  • Access: public

SimpleTemplate is a tag-substitution engine with malleable tag formats,
fast parsing based on a single regular expression, and a simple,
object-based approach to tag naming. SimpleTemplate is useful
when XT is considered overkill, mostly in short, non-strict templates
that do not represent a complete document or page.

The tag format is determined
during the creation of the SimpleTemplate object, by passing one
of the constants defined in this package as the second parameter
to the constructor method. This defines the $use_delim property
which points to the specified delimiters in the $delim property
array. New delimiters may be added by adding them to the $delim
array, then calling the setDelim() method.

Templates can be passed as either a file name or a string. Files
that are parsed more than once will be stored in the internal
$cache array, so they will only be read from the filesystem
the first time. As a general rule, SimpleTemplate template files
are given a .spt extension (if you're geeky enough -- like me --
you can pronounce it "SimPlaTe").

Tags take the form:

opening delimiter + object name + separator + property or method + closing delimiter

The separator can be either a dot (.), a colon (:), or a forward-
slash (/). The forward-slash is the easiest to type, I find. :)

If an object is passed to the fill() method, then that object
is considered the 'default', and you can omit the object name
and separator when referring to its properties and methods. In
this case, the tag syntax becomes:

opening delimiter + property or method + closing delimiter

Inline PHP code is also allowed in templates, but it is discouraged
in practice. It can be useful however, when you want to make
formatting transformations similar to what is possible with the
XT transform tag. In this case, a short block of PHP code at
the top of the file is sufficient. Also note that the PHP
code is evaluated in the namespace of the SimpleTemplate fill()
method. To refer to the default object, use $obj, to refer to
properties of the SimpleTemplate object itself, use $this.
To refer to global objects, use the PHP global command first.

See the example for an example template.

Note: Methods called in templates DO NOT receive any parameters.
Please be aware of this when using this functionality.

Also Note: Some SAF packages rely on a global $simple object
being available to them. As a result, this is considered a
"core" SAF package.

New in 1.2:
- Added SIMPLE_TEMPLATE_DELIM_COMMENTS constant and delimiters,
which make use of HTML comment tags of the form
<!-- put: tagname --> to denote tag substitutions.
- Added the ability to specify an alternate delimiter on a
per-template basis using a comment at the very beginning of
the template file containing the name of the constant that
points to the alternate delimiter. For example, you could
use the new HTML comment delimiters by starting off your
template document with
<!-- SIMPLE_TEMPLATE_DELIM_COMMENTS -->.

New in 1.4:
- Added the ability to include basic looping and conditional
logic in the templates via new {loop obj.list} {end loop}
- Added I18n capabilities via an {intl} tag.
- Added {php} tag. Takes a PHPShorthand expresssion and
returns its output.
- Added an {alt} tag. This creates an saf.Misc.Alt object
that can be referred to via {alt/next} and {alt/current}.
- See example for usage of the new tags.

New in 1.6:
- Added {if condition} {end if} tags, and the ability to
nest loops and ifs within other loops and ifs. Note
that there is no {elseif} or {else} at this point.
- Added the {exec} tag, which is the equivalent to the
{php} tag, but does not return any output.
- Added {filter function_name} {end filter} tags that
change the function that other tags are passed through
when added to the output. The default is
{filter htmlentities_compat} which does not need to be
called at the start, since it is automatic. Another
useful filter is {filter urlencode}. If you do not
want filtering of a section of your template, use
{filter none}.
- Added {inc} and {spt} tags. {inc} includes a file
for its data, while {spt} includes a file but runs
fill() on its contents before adding them to the output.
Both tags also take ordinary variables and aliases,
such as {inc obj/some_var} or
{spt CONSTANT_THAT_CONTAINS_SOME_TEMPLATE}.
- Removed the loop() method and the simple_template_loop()
function.
- Added {form} and {box} tags, to call loader_form() and
loader_box(), respectively.

New in 1.8:
- Fixed a bug that caused the 'end filter' token to be passed
to the filter function.
- Added comment tags, which do not get passed to the client.
The syntax is two dashes and a space at the start, then
a space and two dashes at the end, for example:
{-- this is a comment --}.

New in 2.0:
- Added the ability to specify an object to pass in lieu of
the default $obj when called {spt}. The syntax is
{spt template.spt param/name} where "param/name" represents
the path to a value or object within the register.
- Added the ability to resolve paths such as 'obj' or 'loop'
to their respective objects within the register.
- Added the ability to pass key names from the register to
the {loop} tag. For example: {loop obj} or {loop loop}
(AKA loop through the items in the current loop item).
- Added the ability to call on values from an outer loop
from within a nested loop, using {parent/value} as the
new path name.

New in 2.2:
- Fixed a bug looping through 2D arrays, where it would start
to loop through _properties, _index, _total, _key, etc.

New in 2.4:
- You can now pass parameters to box calls, via the following
syntax: {box path/to/box?param1=value&param2=value2}
- You can also include dynamic values in your box calls via
the following syntax: {box path/to/box?param=[expression]}
The []'s denote an inline expressions which are passed to
determine() and substituted for the results. They can only
be used in place of parameter values, not anywhere else in
the box calling syntax.
- Added an else clause to if statements, in the form of an
{if else} tag, which operates in the same way as an ordinary
{if statement} tag does, except that it should aways come
directly after the ordinary if statement (if you need it).


Usage Example


<?php

$simple 
= new SimpleTemplate ('inc/html'SIMPLE_TEMPLATE_DELIM_CURLY);

// create some fake objects
$person1 = new StdClass;
$person1->firstname 'Joe';
$person1->lastname 'Smith';
$person1->age '29';

$person2 = new StdClass;
$person2->firstname 'Sandy';
$person2->lastname 'MacDonald';
$person2->age '25';

// load them into an array
$people = array ($person1$person2);

// create a global object to refer to as well
$loader->import ('saf.Misc.Alt');
$colours = new Alt ('#eeeeee''#ffffff');

foreach (
$people as $person) {
    echo 
$simple->fill ('
        '
,
        
$person
    
);
}

// example with conditions and looping
// for more info about if and loop syntax, see the package saf.Misc.Shorthand
// note that you can put a single loop inside a condition and vice versa,
// but you cannot embed a loop within a loop, nor a condition within another.
echo $simple->fill ('
    {if count (obj[people]) gt 0}
        

        
    {end if}'
,
    array (
        
'listTitle' => 'Employees',
        
'people' => array (
            array (
                
'firstname' => 'Joe',
                
'lastname' => 'Smith',
            ),
            array (
                
'firstname' => 'Sandy',
                
'lastname' => 'Miller',
            ),
        ),
    )
);

$data = array (
    
'title' => 'Matrix',
    array (
        array (
'one''two'),
        array (
'three''four'),
        array (
'five''six'),
        array (
'seven''eight'),
        array (
'nine''ten'),
        array (
'eleven''twelve'),
    ),
);

echo 
template_simple ('
    {alt #ffffff #cccccc}
    
    '
,
    
$data
);


// Example of if/else usage:

$foo mt_rand (01);
echo 
template_simple ('

  {if obj[foo]}
    YES ({foo})
  {end if}

  {if else}
    NO ({foo})
  {end if}

'
, array ('foo' => $foo));

?>

Return to Top



Properties


$path

  • Access: public

The path to the template directory.


$cache = array ()

  • Access: private

A cache for templates read from files, so if they are
called a second or third time, we don't have to read them from
the file system again.


$delim = array (
        array (
'##', '##'),
        array (
'\\{', '\\}'),
        array (
'\\(', '\\)'),
        array (
'\\.\\.\\.', '\\.\\.\\.'),
        array (
'<\\!-- put: ', ' -->'),
        array (
'<spt>', '<\\/spt>'),
        array (
'<% ', ' %>'),
    )

  • Access: public

List of predefined delimiters. A delimiter is a
2-element array with an opening and a closing delimiter
string (must be valid as a regular expression, no escaping
is done for you). Predefined delimiters are: double-pound
(ie. ##tag##), curly braces (ie. {tag}), round braces
(ie. (tag)), and triple-dots (ie. ...tag...).


$delim_literal = array (
        array (
'##', '##'),
        array (
'{', '}'),
        array (
'(', ')'),
        array (
'...', '...'),
        array (
'<!-- put: ', ' -->'),
        array (
'<spt>', '</spt>'),
        array (
'<% ', ' %>'),
    )

  • Access: public

List of predefined delimiters, represented minus
the slashes in place for insertion into regular expressions,
as the $delim list is.


$use_delim

  • Access: public

Points to which delimiters to use (from the $delim
array).


$filter = 'htmlentities_compat'

Default filter for inserted vars is htmlentities_compat.


$_ignoreUntilEndLoop = false

Whether to ignore output until an end loop is found.


$_bufferUntilEndLoop = false

Whether to buffer output until an end loop is found.


$_ignoreUntilEndIf = false

Whether to ignore output until an end if is found.


$_loopList = array ()

List of loops.


$_loopBuffer = ''

Loop buffer.


$_structCount = 0

Count of structs (ifs and loops).

Return to Top



Methods


SimpleTemplate ($path = 'inc/html', $use_delim = SIMPLE_TEMPLATE_DELIM_CURLY)

  • Access: public

Constructor method.


setDelim ($use_delim = SIMPLE_TEMPLATE_DELIM_CURLY)

  • Access: public

Sets $use_delim to the specified value.


getPath ()

  • Access: public
  • Return: string

Returns the $path property or the current directory
if the $path is empty.


determine ($var, $obj)

  • Access: public
  • Return: mixed

Determines the value to return based on the
specified $obj and $var.


fill ($tpl, $obj = '')

  • Access: public
  • Return: string

Fills the template and returns it. This is the mainloop
of the parser.


_fill ($tpl, $obj)


register ($name, $var)

Return to Top

Copyright © 2008 Sitellite CMS Project

Powered by Sitellite 5.0 Content Management System