1. Go to this page and download the library: Download wernerwa/pat-template library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
wernerwa / pat-template example snippets
$tmpl = new patTemplate();
$tmpl->readTemplatesFromInput('my-templates.tmpl');
$tmpl->displayParsedTemplate('page');
$tmpl = new patTemplate();
$tmpl->setRoot('/path/to/templates');
$tmpl->readTemplatesFromInput('my-template.tmpl');
$tmpl = new patTemplate();
$tmpl->readTemplatesFromInput('my-template.tmpl');
$tmpl->addVar('page', 'NAME', 'Stephan');
$tmpl->displayParsedTemplate();
$tmpl = new patTemplate();
$tmpl->readTemplatesFromInput('my-template.tmpl');
$tmpl->addRows('entry', $data, 'USER_');
$tmpl->displayParsedTemplate();
class User {
public $id;
public $name;
public function __construct($id, $name) {
$this->id = $id;
$this->name = $name;
}
}
$schst = new User('schst', 'Stephan Schmidt');
$tmpl = new patTemplate();
$tmpl->readTemplatesFromInput('user-info.tmpl');
$tmpl->addObject('user-info', $schst, 'USER_');
class User {
private $id;
private $name;
public function __construct($id, $name) {
$this->id = $id;
$this->name = $name;
}
/**
* This method will be invoked by patTemplate if the
* object is passed to addObject()
*/
public function getVars() {
return array(
'id' => $this->id,
'name' => $this->name
);
}
}
$tmpl = new patTemplate();
$tmpl->setOption('allowFunctionsAsDefault', true);
$tmpl = new patTemplate();
$tmpl->readTemplatesFromInput('myPage.tmpl');
$tmpl->addVar('header', 'TITLE', 'Page title');
$tmpl->displayParsedTemplate();
$tmpl = new patTemplate();
$tmpl->readTemplatesFromInput('my-templates.tmpl');
$tmpl->displayParsedTemplate('page');
$tmpl = new patTemplate();
$tmpl->setRoot('/path/to/templates');
$tmpl->readTemplatesFromInput('my-template.tmpl');
$tmpl = new patTemplate();
$tmpl->setOption('allowFunctionsAsDefault', true);
$tmpl = new patTemplate();
$tmpl->readTemplatesFromInput('MyTemplates.tmpl', 'File');
$tmpl = new patTemplate();
$tmpl->setRoot('/path/to/templates', 'File');
$tmpl->readTemplatesFromInput('myTemplate.tmpl');
$string = '<patTemplate:tmpl name="string">This template has been parsed from a string `<patTemplate:tmpl name="too">`, as well as this.</patTemplate:tmpl></patTemplate:tmpl>';
$tmpl = new patTemplate();
$tmpl->readTemplatesFromInput( $string, 'String' );
tmpl = new patTemplate();
$tmpl->setRoot('mysql://root:@localhost/test', 'DB');
$tmpl->readTemplatesFromInput("SELECT content FROM templates WHERE id='foo'", 'DB');
$tmpl = new patTemplate();
$tmpl->setRoot('templates');
$tmpl->applyOutputFilter('StripWhitespace');
$tmpl->readTemplatesFromInput('myPage.tmpl');
// Will not strip whitespace
$html = $tmpl->getParsedTemplate('page');
// Will strip whitespace
$compressed = $tmpl->getParsedTemplate('page', true);
$tmpl->applyInputFilter('StripComments');
$tmpl = new patTemplate();
$tmpl->readTemplatesFromInput('page.tmpl');
$tmpl->setNamespace('MyNamespace');
$tmpl->setNamespace(array('MyNamespace', 'pat'));
$tmpl = new patTemplate();
$tmpl->setBasedir( "templates" );
$tmpl->readTemplatesFromFile( "superherolist.tmpl" );
$db = DB::connect('mysql://user:pass@localhost/myDb');
$query = "SELECT id, superhero, real_name FROM secretIdentities ORDER BY superhero";
$result = $db->getAll($query, DB_FETCHMODE_ASSOC);
$tmpl->addRows( "list_entry", $result);
$tmpl->displayParsedTemplate();
// data to display
$data = array(
array( "real_name" => "Clark Kent", "superhero" => "Superman" ),
array( "real_name" => "Bruce Wayne", "superhero" => "Batman" ),
array( "real_name" => "Kyle Rayner", "superhero" => "Green Lantern" ),
array( "real_name" => "Wally West", "superhero" => "The Flash" ),
array( "real_name" => "Linda Danvers", "superhero" => "Supergirl" ),
);
// number of columns per row
$cols = 3;
// calculate number of rows
$rows = ceil(count($data)/$cols);
$counter = 0;
// loop for each row
for ($i = 0; $i < $rows; $i++) {
// clear cells from last row
$tmpl->clearTemplate( "cell" );
// put data for one row in a new array
$rowData = array();
for ($j = 0; $j < $cols; $j++) {
if (isset($data[$counter]))
array_push($rowData, $data[$counter++]);
}
// add the data of one row to the cells
$tmpl->addRows( "cell", $rowData );
// parse this row and append the data to previously parsed rows
$tmpl->parseTemplate( "row", "a" );
}
$tmpl->displayParsedTemplate();
$tmpl->readTemplatesFromFile( "myTemplate.tmpl" );
$defaultId = 19;
$query = "SELECT id, superhero FROM heroes ORDER BY superhero";
$result = mysqli_query($link, $query);
$entries = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// determine, whether entry should be selected by default
if( $row["id"] ** $defaultId )
$row["selected"] = "yes";
else
$row["selected"] = "no";
// add the entry to all other entries
array_push( $entries, $row );
}
// add all entries to the drop down menu
$tmpl->addRows( "dropdown_entry", $entries );
// display the page
$tmpl->displayParsedTemplate( "page" );
/**
* patTemplate modfifier Truncate
*
* @package patTemplate
* @subpackage Modifiers
* @author Stephan Schmidt <[email protected]>
*/
class patTemplate_Modifier_Truncate extends patTemplate_Modifier
{
/**
* truncate the string
*
* @param string value
* @param array value
* @return string modified value
*/
public function modify( $value, $params = array() )
{
/**
* no length specified
*/
if( !isset( $params['length'] ) )
return $value;
/**
* is shorter than the length
*/
if( $params['length'] > strlen( $value ) )
return $value;
return substr( $value, 0, $params['length'] ) . '...';
}
}
/**
* patTemplate Reader that reads from a file
*
* @package patTemplate
* @subpackage Readers
* @author Stephan Schmidt <[email protected]>
*/
class patTemplate_Reader_File extends patTemplate_Reader
{
/**
* reader name
* @var string
*/
protected $_name ='File';
/**
* read templates from any input
*
* @final
* @param string file to parse
* @param array options, not implemented in current versions, but future versions will allow passing of options
* @return array templates
*/
public function readTemplates($input, $options = array())
{
$this->_currentInput = $input;
$fullPath = $this->_resolveFullPath( $input );
$content = file_get_contents( $fullPath );
$templates = $this->parseString( $content );
return $templates;
}
/**
* resolve path for a template
*
* @param string filename
* @return string full path
*/
private function _resolveFullPath( $filename )
{
$baseDir = $this->_options['root'];
$fullPath = $baseDir . '/' . $filename;
return $fullPath;
}
}
/**
* patTemplate StripWhitespace output filter
*
* Will remove all whitespace and replace it with a single space.
*
* @package patTemplate
* @subpackage Filters
* @author Stephan Schmidt <[email protected]>
*/
class patTemplate_OutputFilter_StripWhitespace extends patTemplate_OutputFilter
{
/**
* filter name
*
* @abstract
* @var string
*/
protected $_name = 'StripWhitespace';
/**
* remove all whitespace from the output
*
* @param string data
* @return string data without whitespace
*/
public function apply( $data )
{
$data = str_replace( "\n", ' ', $data );
$data = preg_replace( '/\s\s+/', ' ', $data );
return $data;
}
}
$tmpl = new patTemplate();
$tmpl->setRoot( 'templates' );
$tmpl->applyOutputFilter( 'StripWhitespace' );
$tmpl->readTemplatesFromInput( 'page.tmpl', 'File' );
/**
* output filter will be applied here
*/
$tmpl->displayParsedTemplate();
/**
* patTemplate StripComments input filter
*
* Will remove all HTML comments.
*
* @package patTemplate
* @subpackage Filters
* @author Stephan Schmidt <[email protected]>
*/
class patTemplate_InputFilter_StripComments extends patTemplate_InputFilter
{
/**
* filter name
*
* @var string
*/
protected $_name = 'StripComments';
/**
* compress the data
*
* @param string data
* @return string data without whitespace
*/
public function apply($data) {
$data = preg_replace('°<!--.*-->°msU', '', $data);
return $data;
}
}
$tmpl = new patTemplate();
$tmpl->setRoot('templates');
$tmpl->applyInputFilter('StripComments');
$tmpl->readTemplatesFromInput('page.tmpl', 'File');
/**
* output filter will be applied here
*/
$tmpl->displayParsedTemplate();
/**
* patTemplate function that calculates the current time
* or any other time and returns it in the specified format.
*
* @package patTemplate
* @subpackage Functions
* @author Stephan Schmidt <[email protected]>
*/
class patTemplate_Function_Time extends patTemplate_Function
{
/**
* name of the function
* @var string
*/
protected $_name = 'Time';
/**
* call the function
*
* @param array parameters of the function (= attributes of the tag)
* @param string content of the tag
* @return string content to insert into the template
*/
public function call( $params, $content )
{
if( !empty( $content ) )
{
$params['time'] = $content;
}
if( isset( $params['time'] ) )
{
$params['time'] = strtotime( $params['time'] );
}
else
{
$params['time'] = time();
}
return date( $params['format'], $params['time'] );
}
}
$tmpl = new patTemplate();
$tmpl->setRoot( 'templates' );
/**
* Use a template cache based on file system
*/
$tmpl->useTemplateCache( 'File', array(
'cacheFolder' => './tmplCache',
'lifetime' => 60 )
);
$tmpl->readTemplatesFromInput( 'page.tmpl', 'File' );
$tmpl->displayParsedTemplate();
/**
* patTemplate Template cache that stores data on filesystem
*
* Possible parameters for the cache are:
* - cacheFolder : set the folder from which to load the cache
* - lifetime : seconds for which the cache is valid, if set to auto, it will check
* whether the cache is older than the original file (if the reader supports this)
*
* @package patTemplate
* @subpackage Caches
* @author Stephan Schmidt <[email protected]>
*/
class patTemplate_TemplateCache_File extends patTemplate_TemplateCache
{
/**
* parameters of the cache
*
* @var array
*/
protected $_params = array(
'cacheFolder' => './cache',
'lifetime' => 'auto'
);
/**
* load template from cache
*
* @param string cache key
* @param integer modification time of original template
* @return array|boolean either an array containing the templates or false cache could not be loaded
*/
public function load( $key, $modTime = -1 )
{
$filename = $this->_getCachefileName( $key );
if( !file_exists( $filename ) || !is_readable( $filename ) )
return false;
$generatedOn = filemtime( $filename );
$ttl = $this->getParam( 'lifetime' );
if( $ttl ** 'auto' )
{
if( $modTime < 1 )
return false;
if( $modTime > $generatedOn )
return false;
return unserialize( file_get_contents( $filename ) );
}
elseif( is_int( $ttl ) )
{
if( $generatedOn + $ttl < time() )
return false;
return unserialize( file_get_contents( $filename ) );
}
return false;
}
/**
* write template to cache
*
* @param string cache key
* @param array templates to store
* @return boolean true on success
*/
public function write( $key, $templates )
{
$fp = @fopen( $this->_getCachefileName( $key ), 'w' );
if( !$fp )
return false;
flock( $fp, LOCK_EX );
fputs( $fp, serialize( $templates ) );
flock( $fp, LOCK_UN );
return true;
}
/**
* get the cache filename
*
* @param string cache key
* @return string cache file name
*/
private function _getCachefileName( $key )
{
return $this->getParam( 'cacheFolder' ) . '/' . $key . '.cache';
}
}
xhtml
<patTemplate:tmpl name="root">
This is a template that is used to display code.
<patTemplate:phpHighlight>
$i = 0;
while( $i < 10 )
{
echo "This is line $i.<br />";
$i++;
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.