To make life a little easier for myself I would like to build a very simple template engine for my projects. Something I had in mind was to have .html files in a directory that get included to a page using PHP when I want them. So a typical index.php
would look like this:
<?php
IncludeHeader("This is the title of the page");
IncludeBody("This is some body content");
IncludeFooter();
?>
Something along those lines, and then in my template files I'd have:
<html>
<head>
<title>{PAGE_TITLE}</title>
</head>
<body>
But one thing I can't work out how to do is get the parameter passed to the functions and repla开发者_运维技巧ce {PAGE_TITLE}
with it.
Does anyone have a solution or perhaps a better way to do this? Thanks.
In the interests of keeping things simple, why not just use .php files with PHP shorttags instead of {PAGE_TITLE}
or the like?
<html>
<head>
<title><?=$PAGE_TITLE?></title>
</head>
<body>
Then, to isolate the variable space, you can create a template load function which works like this:
function load_template($path, $vars) {
extract($vars);
include($path);
}
Where $vars is an associative array with keys equal to variable names, and values equal to variable values.
Why not just use php?
<html>
<head>
<title><?=$pageTitle; ?></title>
</head>
<body>
The simplest thing to do is something like this:
<?php
function IncludeHeader($title)
{
echo str_replace('{PAGE_TITLE}', $title, file_get_contents('header.html'));
}
?>
As you may understand, PHP is, itself, a template engine. That being said, there are several projects that add the type of templating you're describing. One which you might want to investigate is Smarty Templates. You might also want to check out the article published at SitePoint describing templating engines in general.
This is the trick I've seen some frameworks use:
// Your function call
myTemplate('header',
array('pageTitle' => 'My Favorite Page',
'email' => 'joe@bob.com',
)
);
// the function
function myTemplate($filename, $variables) {
extract($variables);
include($filename);
}
// the template:
<html>
<head>
<title><?=$pageTitle?></title>
</head>
<body>
Email me here<a href="mailto:<?=$email?>"><?=$email?></a>
</body>
</html>
精彩评论