Pure PHP template class.
Nowdays with ZendFramework, Cake or any other MVC framework you have their integrated pure PHP template class - really makes life easier.
I'm not trying to raise the old-flame-war debate : Templating engines vs. Pure PHP templates.
For my point of view there are few advantages for Pure PHP:
- Faster execution
- No need for learning template engine's syntax
- All the functions you need are there in PHP or you just extend the class and write your own
With this engine you can simply use and make your templates with the power of PHP behind you.
Usage - simple example:
PHP Code:
<?php
include 'x3View.php';
// Include the template file
$tmpl = new x3View( 'template/index.php');
// Assign some data
$tmpl->title = "Simple example page";
$tmpl->data = "This is a really simple example!";
// Display the template;
$tmpl->display();
?>
The template:
PHP Code:
<?= $this->title; ?><br />
<?= $this->data; ?>
Displays:
Code:
Simple example page <br />
This is a really simple example!
Advanced usage:
PHP Code:
<?php
include 'x3View.php';
// The sub page
$sub = new x3View( 'template/sub.php' );
$sub->title = "Wow I'm going to be parsed";
$sub_parsed = $sub->parse();
// Main page
$index = new x3View( 'template/index.php' );
$index->sub_page = $sub_parsed;
$index->title = "Wow we included something!";
$index->display();
?>
Now the templates:
sub.php
PHP Code:
I am a sub page. <br />
<?= $this->title ?>
index.php
PHP Code:
Hi! I am an index page! <br />
<?= $this->title; ?> <br />
Below is a parsed sub page: <br />
<?= $this->sub_page; ?>
At last - the output:
Code:
Hi! I am an index page! <br />
Wow we included something! <br />
Below is a parsed sub page: <br />
I am a sub page! <br />
Wow I'm going to be parsed
Usage is simple - simply use it like a Singleton :)
And at last - the class.
PHP Code:
<?php
class x3View {
protected $file;
public function __construct( $file ) {
$this->file = $file;
}
/*
* Output methods
* ------------------------------
*/
public function display() {
require $this->file;
}
public function parse() {
// Start
ob_start();
require( $this->file );
$tmpl = ob_get_contents();
ob_end_clean();
return $tmpl;
}
}
?>