Php templating with codeigniter

codeigniterPHPtemplates

I am currently develop a website application in codeigniter, and I'd like to do something in PHP / CodeIgniter where I can make a common template for separate sections of the website. I was thinking that I would keep the header / footer in a separate php files & include them separately.

The thing I'm not sure about is the content beneath the header and above the footer. This website application will contain a lot of different pages, so I'm having a hard time figuring how what's the best way to do this.

Best Answer

I generally prefer to create a "layout" file rather than having to include both a header and footer on every page. It's more flexible.

Here's a snippet from one of my projects:

ob_start();
include '../views/'.$templateFile;
$pageContent = ob_get_clean();
include '../views/layouts/'.$layoutFile;

All you have to do is enable output buffering, include the template, then call ob_get_clean() to nab the contents of your template and put it into a variable. Once it's in a variable you can include your main layout file, which should echo $pageLayout somewhere inside.

e.g.,

<html>
<head>
    <title>Your Site</title>
</head>
<body>
    <!-- header here -->
    <?= $pageContents ?>
    <!-- footer here -->
</body>
</html>

That said, surely Code Igniter has some kind of templating built in, no? I'm not familiar with it. Edit: Apparently it does not. Kind of silly really; with caching, the performance cost of a nice templating engine is negligible.

Related Topic