Dirt-Simple PHP Templates... Can This Work Without 'Eval'

In PHP file, get {$variable} to do the equivalent of ?php echo $variable; ?

Pretty much trivial with output buffering.

$variable = 'I am a variable';
$output = '';
ob_start();
require 'template.tpl';
$output = ob_get_clean();
echo $output;

php array and html

If you want to replace tags {name} to value with $a = array('name' => 'value'); you can use str_replace();

$filehtml = file_get_contents('file.html');
$array = array('var' => 'value');

foreach($array as $tag => $value)
{
$filehtml = str_replace('{'.$tag.'}', $value, $filehtml);
}

echo $filehtml;

Or you use Smarty (or others).

Where to keep settings of displaying web page? (php/xml/json/ini)

using.ini files is great feature in PHP:

class Template {
private $config;
public function __construct() {
$this->config = parse_ini_file('templates.ini');
}
public function fetch() {
$this->config['default_dir']; // example
}
}
  • Documentation http://php.net/manual/en/function.parse-ini-file.php

According to your comment - loading it's not that fast. But you can always cache .ini files in memory:

class IniFiles {
private static $_files = Array();
public static function parse($file) {
if(isset(self::$_files[$file])) return self::$_files[$file];
self::$_files[$file] = parse_ini_file($file);
return self::$_files[$file];
}
}

class Template {
private $config;
public function __construct() {
$this->config = IniFiles::parse('templates.ini');
}
public function fetch() {
$this->config['default_dir']; // example
}
}

Now it's perfect solution. :)



Related Topics



Leave a reply



Submit