views:

55

answers:

5

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 replace {PAGE_TITLE} with it.

Does anyone have a solution or perhaps a better way to do this? Thanks.

A: 

The simplest thing to do is something like this:

<?php
function IncludeHeader($title)
{
    echo str_replace('{PAGE_TITLE}', $title, file_get_contents('header.html'));
}
?>
Darrell Brogdon
A: 

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.

Tony Miller
+1  A: 

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.

Amber
@Gordon: http://www.mail-archive.com/[email protected]/msg41868.html
Amber
Interesting. Didn't know that. Thanks for the link.
Gordon
+1  A: 

Why not just use php?

<html>
<head>
    <title><?=$pageTitle; ?></title>
</head>
<body>
Januz
A: 

This is the trick I've seen some frameworks use:

// Your function call
myTemplate('header',
    array('pageTitle' => 'My Favorite Page',
          'email' => '[email protected]',
    )
);

// 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>
SeanDowney