tags:

views:

40

answers:

2

I'm using a file, page.php, as an HTML container for several content files; i.e., page.php defines most of the common structure of the page, and the content files just contain the text that's unique to every page. What I would like to do is include some PHP code with each content file that defines metadata for the page such as its title, a banner graphic to use, etc. For example, a content file might look like this (simplified):

<?php $page_title="My Title"; ?>
<h1>Hello world!</h1>

The name of the file would be passed as a URL parameter to page.php, which would look like this:

<html>
  <head>
    <title><?php echo $page_title; ?></title>
  </head>
  <body>
    <?php include($_GET['page']); ?>
  </body>
</html>

The problem with this approach is that the variable gets defined after it is used, which of course won't work. Output buffering also doesn't seem to help.

Is there an alternate approach I can use? I'd prefer not to define the text in the content file as a PHP heredoc block, because that smashes the HTML syntax highlighting in my text editor. I also don't want to use JavaScript to rewrite page elements after the fact, because many of these pages don't otherwise use JavaScript and I'd rather not introduce it as a dependency if I don't have to.

+2  A: 

Most people store the output of the included page into another variable. Have you tried putting all the content of the included page into the output buffer, then storing the ob_get_clean() into a variable like $page_html, then having your page look like this:

<?php include($_GET['page']); ?>
<html>
  <head>
    <title><?php echo $page_title; ?></title>
  </head>
  <body>
    <?php echo $page_html; ?>
  </body>
</html>

Edit: So the second page would look something like this:

<?php
$page_title="My Title";
ob_start();
?>
<h1>Hello world!</h1>
<?php $page_html=ob_get_clean(); ?>
animuson
+1  A: 

The best thing I can think of would be to separate the inclusion of the file from the rendering. So your template looks like this:

<?php include($_GET['page']); ?>
<html>
  <head>
    <title><?php echo $page_title; ?></title>
  </head>
  <body>
     <?php renderPage() ?>
  </body>
</html>

And the file you are including looks like this:

<?php
$page_title="My Title";
function renderPage() {
?>
<h1>Hello world!</h1>
<?php 
}
?>

This is also nice since you can pass parameters to renderPage() so that the template can pass info along to the page it is including.

Eric Petroelje