Dr. Doom
10.01.2005, 11:42
Ich habe für ein anderes Projekt eine Art Minimalklasse entwickeln dürfen, die im Prinzip nix kann ausser Programmierlogik und Design zu trennen. Das besondere ist, dass es ohne eval auskommt, sehr schnell ist und die Klasse viel kleiner als 1 kb ist mit Kommentaren. Evtl. ist das ja eine kleine Inspiration für andere :).
<?php
/**
* Just a simple Template Class
*/
class tpl
{
var $_vars = array();
/**
* Assign vars
* @input: string $key the key to replace
* @input: string $value the value which should be insert
*/
function vars($key, $value)
{
$this->_vars['{'.$key.'}'] = $value;
}
/**
* Parse the template
* @input: string $tpl the filename of the template
* @return: string the parsed template
*/
function parse($tpl)
{
$template = @file_get_contents('templates/'.$tpl) OR exit('Could not open template: '.$tpl);
return str_replace(array_keys($this->_vars), array_values($this->_vars), $template);
}
}
?>
Und die Anwendung:
<?php
$tpl = new tpl();
$tpl->vars('VAR1', $variable1);
$tpl->vars('VAR2', $variable2);
echo $tpl->parse('template.html');
?>
In dem Template werden dann {VAR1} und {VAR2} durch die angegebenen Variabeln ersetzt. Viel Spass :)
<?php
/**
* Just a simple Template Class
*/
class tpl
{
var $_vars = array();
/**
* Assign vars
* @input: string $key the key to replace
* @input: string $value the value which should be insert
*/
function vars($key, $value)
{
$this->_vars['{'.$key.'}'] = $value;
}
/**
* Parse the template
* @input: string $tpl the filename of the template
* @return: string the parsed template
*/
function parse($tpl)
{
$template = @file_get_contents('templates/'.$tpl) OR exit('Could not open template: '.$tpl);
return str_replace(array_keys($this->_vars), array_values($this->_vars), $template);
}
}
?>
Und die Anwendung:
<?php
$tpl = new tpl();
$tpl->vars('VAR1', $variable1);
$tpl->vars('VAR2', $variable2);
echo $tpl->parse('template.html');
?>
In dem Template werden dann {VAR1} und {VAR2} durch die angegebenen Variabeln ersetzt. Viel Spass :)