开发者

What is the best way to include a php file as a template?

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 thi开发者_C百科s? 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.


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'.


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); ?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜