tags:

views:

50

answers:

2

I have simple template that's html mostly and then pulls some stuff out of SQL via PHP and I want to include this template in three different spots of another php file. What is the best way to do this? Can I include it and then print the contents?

Example of template:

Price: <?php echo $price ?>

and, for example, I have another php file that will show the template file only if the date is more than two days after a date in SQL.

A: 

Put your data in an array/object and pass it to the following function as a second argument:

function template_contents($file, $model) {
    if (!is_file($file)) {
        throw new Exception("Template not found");
    }
    ob_start();
    include $file;
    $contents = ob_get_contents();
    ob_end_clean();

    return $contents;
}

Then:

Price: <?php echo template_contents("/path/to/file.php", $model); ?>
Artefacto
Worked great. Thanks!
Jon
@Jon You may want to start accepting the question you make; so after you haven't accepted any.
Artefacto
+1  A: 

The best way is to pass everything in an associative array.

class Template {
    public function render($_page, $_data) {
        extract($_data);
        include($_page);
    }
}

To build the template:

$data = array('title' => 'My Page', 'text' => 'My Paragraph');

$Template = new Template();
$Template->render('/path/to/file.php', $data);

Your template page could be something like this:

<h1><?php echo $title; ?></h1>

<p><?php echo $text; ?></p>

Extract is a really nifty function that can unpack an associative array into the local namespace so that you can just do stuff like echo $title;.

Edit: Added underscores to prevent name conflicts just in case you extract something containing a variable '$page' or '$data'.

Lotus Notes