BradTrupp.com --
Tags --
Old Articles -- One Line Template Engine (PHP)
One Line Template Engine (PHP)
(2007/11/17)
A One Line Template Engine in PHP
This is a really clever example of using a single line of PHP to fill in a HTML template and output a web page.
I found the original in the forums at http://www.webmasterworld.com/.
The one line engine --
print preg_replace("/\{([^\{]{1,100}?)\}/e","$$1",file_get_contents("template.tpl"));
|
It works by finding any string starting with an opening brace and ending with a closing brace and substituting the php variable with the same name.
An example of the template file -- template.tpl -- as used for this example.
<html>
<head>
<title>{title}</title>
</head>
<body>
<h1>{header}</h1>
{text}
</body>
</html>
|
This template has three variables defined -- {title}, {header}, and {text}.
Using the template engine in its simpliest form.
$title="The One Line Template Engine Example";
$header="See this Example Work.";
$text="Magically all the placeholders are replaced!";
print preg_replace("/\{([^\{]{1,100}?)\}/e","$$1",file_get_contents("template.tpl"));
|
Elegantly simple?
Tags: Old Articles
Share: Del.icio.us | Digg | Facebook | Google Bookmarks | Reddit | Technorati | Twitter | Windows Live | Yahoo! My Web