简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM