Forum Moderators: coopster

Message Too Old, No Replies

The One Line Template Engine!

Part 2, revised....

         

trillianjedi

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

WebmasterWorld Senior Member 10+ Year Member



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?";

tangor

10:58 pm on Jul 4, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The revisit to things that work is excellent. Thanks!

Dimitri

12:20 pm on Jul 5, 2018 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month



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).

trillianjedi

10:46 am on Jul 18, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



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).