Matt
Matt

Reputation: 1131

Including template files and dynamically changing variables within them

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.

Upvotes: 1

Views: 265

Answers (5)

SeanDowney
SeanDowney

Reputation: 17762

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>

Upvotes: 0

Januz
Januz

Reputation: 527

Why not just use php?

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

Upvotes: 1

Amber
Amber

Reputation: 527123

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.

Upvotes: 1

Tony Miller
Tony Miller

Reputation: 9159

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.

Upvotes: 0

Darrell Brogdon
Darrell Brogdon

Reputation: 6973

The simplest thing to do is something like this:

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

Upvotes: 0

Related Questions