Welcome to WebmasterWorld Guest from 54.81.69.220

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

The One Line Template Engine!

Part 2, revised....

     
4:37 pm on Jul 4, 2018 (gmt 0)

Senior Member

WebmasterWorld Senior Member trillianjedi is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Apr 15, 2003
posts: 7256
votes: 3


Hi all,

I utterly love this little gem from some years back:

[webmasterworld.com...]

... and have used it pretty much forever since. But it stopped working some time ago (PHP 6 or maybe 7).

Anyway I got it working again, so for anyone interested:-

The php v7 friendly engine itself:-

print preg_replace_callback("/\€([^\{]{1,100}?)\€/",
function ($matches){return $GLOBALS[$matches[1]];}, file_get_contents("template.tpl"));


Refer back to the original thread for the explanation as to how this works. You'll see I changed the original squiggly brackets for euro signs, as I found any inline JavaScript would get messed up otherwise. So templates would look something like:-

<html>
<head>
<title>€title€</title>
</head>
<body>
<h1>€header€</h1>
€text€
</body>
</html>


You set the variables with, eg:

$title="Example page";
$header="My Examples";
$text="See the placeholders replaced?";
10:58 pm on July 4, 2018 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member tangor is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Nov 29, 2005
posts:9889
votes: 967


The revisit to things that work is excellent. Thanks!
12:20 pm on July 5, 2018 (gmt 0)

Senior Member

WebmasterWorld Senior Member Top Contributors Of The Month

joined:Nov 13, 2016
posts:963
votes: 226


You can also do:
$var=array(
"€title€"=>"Example page",
"€header€"=>"My Examples",
"€text€"=>"See the placeholders replaced?"
);

echo str_replace(array_keys($var),array_values($var),file_get_contents("template.tpl"));

Credit to my PHP Mentor, UL :)

It might be less friendly, but it's faster because:
- it avoid calling a function for each single match,
- no use of regexp, which is a complex operation,
- can be used with case insensitive, if used with str_ireplace
- use of local variable, instead of $GLOBALS (faster),

There is also an issue using $GLOBALS because you can end outputting values by mistake.

Let's say that in your GLOBALS scope, you have a variable "header" used for something else. You can have a conflict.(Also, imagine if your tpl file has been compromised. Always double check variables before using/printing them).
10:46 am on July 18, 2018 (gmt 0)

Senior Member

WebmasterWorld Senior Member trillianjedi is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Apr 15, 2003
posts: 7256
votes: 3


I like that Dimitri - not only faster, but also means this can be used within a function (cleanly), which the original cannot (due to the use of globals).