Created
May 1, 2012 15:21
-
-
Save jgarber623/2568768 to your computer and use it in GitHub Desktop.
Basic layout/view-style templating with PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' ); | |
?> |
I think a number of PHP frameworks use this approach. I know CakePHP does, even using the $content_for_layout naming convention.
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
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.