PHP Classes

Template parser: Template engine with tags defined by another class

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 384 All time: 6,707 This week: 69Up
Version License PHP version Categories
template-parser 1.2GNU Lesser Genera...4.0Templates
Description 

Author

This class implements a template engine with tags defined by another class.

It can parse a template and extract the names of tag functions defined within tags delimiter characters.

The parser class calls a separate handler class with functions with the same of of the template tags to return the processed tag output.

The template parser class returns the processed template as a string.

The tag delimiter characters can be customized.

Picture of Roger Baklund
  Performance   Level  
Name: Roger Baklund <contact>
Classes: 7 packages by
Country: Norway Norway
Innovation award
Innovation award
Nominee: 4x

Example

<?php
error_reporting
(E_ALL);
ini_set('display_errors',1);

include(
'template_parser.class.php');

class
MyResolver { # simple demo resolver
 
function __construct() {
   
$this->date_format = 'Y-m-d';
  }
  function
this($data) {
    return
$this->$data;
  }
  function
php($data) {
   
ob_start();
    eval(
$data);
   
$out = ob_get_contents();
   
ob_end_clean();
    return
$out;
  }
  function
upper($data) {
    return
strtoupper($data);
  }
  function
date_format($data) {
   
$this->date_format = $data;
  }
  function
date($data) {
    if(!
$data) $data = 'now';
    return
date($this->date_format,strtotime($data));
  }
}

$s = <<<'EOD'
<div><?date_format d/m-Y?>
<p>Hello <?php $a = "world"; echo $a; ?>, today is <?date?>, yesterday was <?date yesterday?></p>
<p><?upper How do you do??></p>
<p>You can <?upper nest <?php echo 'tags';?> within ?>other tags,
   even within <?php echo '<?upper php?> strings!';?></p>
<p>Because all the resolvers are within the same class,
   they can <?php echo $this->upper('access eachother');?>.</p>
<p>The current date format is '<?this date_format?>'</p>
</div>
EOD;

echo
'<pre>'.htmlspecialchars($s)."\n\n -----> \n\n";
$tp = new template_parser(new MyResolver(),'<?','?>',' ');
echo
htmlspecialchars($tp->parse($s));
echo
'</pre>';
?>


  Files folder image Files (2)  
File Role Description
Plain text file template_parser.class.php Class The main class
Plain text file test_template_parser.php Example Test/demo for template parser

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 0%
Total:384
This week:0
All time:6,707
This week:69Up