Skip to content

Instantly share code, notes, and snippets.

@jgarber623
Created May 1, 2012 15:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jgarber623/2568768 to your computer and use it in GitHub Desktop.
Save jgarber623/2568768 to your computer and use it in GitHub Desktop.
Basic layout/view-style templating with PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $page_title; ?></title>
</head>
<body>
<?php echo $content_for_layout; ?>
</body>
</html>
<?php
$page_title = 'Welcome to my website!';
ob_start();
?>
<h1>Welcome to my website!</h1>
<p>It's created using PHP's output buffering control.</p>
<?php
$content_for_layout = ob_get_clean();
require_once( '_layout.php' );
?>
@jgarber623
Copy link
Author

I've spent enough time working in Rails to love how it handles layouts and views. I want to do something like that in PHP, so after digging around the Internet, I figured out how to make this happen.

The example above uses PHP's output buffering control which you will have to make sure is on for this example to work.

@snookca
Copy link

snookca commented May 1, 2012

I think a number of PHP frameworks use this approach. I know CakePHP does, even using the $content_for_layout naming convention.

@jgarber623
Copy link
Author

Oh yeah, I came across that convention (in CakePHP, specifically) while I was researching how to do this without using a framework. It's rare that I dabble in PHP these days, so this was a pretty new thing for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment