Web Hosting Talk







View Full Version : Easy way to parse certain vars for a template?


lexington
12-09-2007, 12:24 AM
Hello, could anyone give me a simple example on how to make a php variable display on a template and what to place in that template for it to display properly? I created a language file with text and I thought a simple echo would do the trick until I realized that the template doesn't know what the variable is since it doesn't have an include commands in the file. I basically want it so it would be like:

php file

$test = 'blah';

template file output displays

blah

Thanks.

bear
12-09-2007, 12:27 AM
Here's one way of several:

<?php
$variable = blah;
echo 'this is my variable: ' . $variable . 'in the page';
?>

lexington
12-09-2007, 12:32 AM
Yeah sorry for the confusion I meant that I would like a php file to contain the variable and a separate template file to display the contents of that variable without having to use an include code. You know like most custom scripts out there like phpBB where the variables are in php and the template displays {PAGE_TITLE} and {PAGE_TITLE} is parsed on the page as the variable in the php file.

lexington
12-09-2007, 01:02 AM
I am looking at a few scripts that I have installed that use templates and they all use a custom function for this.

tiamak
12-10-2007, 10:35 AM
ah so u need some template engine?
really basic code might look like:

template file...

<html>
<body>
foo: {foo}<br />
a: {something}<br />
b: {somethingelse}<br />
</body>
</html>


php file...

<?php
class tpl {
var $tmpl;
var $dane;
function tpl ($name) {
$this->tmpl = implode('', file($name));
$this->dane = Array();
}

function add($name, $value = '') {
if (is_array($name)) {
$this->dane = array_merge($this->dane, $name);
}
else if (!empty($value)) {
$this->dane[$name] = $value;
}
}
function execute() {
$this->tmpl = preg_replace('/{([^\\!][^}]+)}/e', '$this->dane["\\1"]', $this->tmpl);
return $this->tmpl;
}
}
// above should be put into a separate file

#read template file
$html = new tpl('blah.tpl');

# add single variable to ur template file;
$bar='bar';
$html->add('foo',$bar);

#add array
$out['something']='lalala';
$out['somethingelse']='blah blah';
$html->add($out);

# output code
echo $html->execute();
?>


ofcourse this is very lame example - in "real life" you would need to add to your template engine at least while/for loops and if/else statements...
but instead of wasting time for own template engine better use "smarty" or something similar ;)