Jump to content

[SOLVED] How to design a template structure?


psyickphuk

Recommended Posts

At the moment my index page is basically the template along the lines of:

 

<?

//script to determine what page to include

include ("$page.php");

?>

 

<html>

<head>

<body>

<header>

<menu>

<? function article(); ?>

 

<footer>

</body>

</html>

 

And the included file "$page.php" has its contents/script inside a function - article()

 

Anyway this all works fine but now I want to start including dynamic content in the page title and meta tags etc so I need to change how I work it. I would rather have the pages loading a template rather than the template loading the pages I think. Except then I end up with loads of separate files e.g a header file. menu file, sidepanel file, footer etc.

 

Anyone got any suggestions for a neat way of doing this? Oh and I don't want to use 3rd party templating engine, i want to do it so I understand what's going on ;)

When I do template systems I use the following method.

 

Have a file called template.html that has a structure something like this:

 

<html>
<head>
<title>
[PAGE-TITLE]
</title>
<meta name="description" content="[META-DESCRIPTION]">

</head>
<body>
[CONTENT]

</body>
</html>

 

Then each time you want to use the template, read the file into a variable and do the following:

 

$file = str_replace("[PAGE-TITLE]", "Page Title Here", $file);
$file = str_replace("[META-DESCRIPTION]", "Page meta description goes here", $file);
$file = str_replace("[CONTENT]", article(), $file);

echo $file;

 

You can add any variables into your template making this sytem quite powerful if used correctly.

 

I hope this helps.

Hi thanks that's great I have started experimenting with this format and it works well except for when I get to:

 

$file = str_replace("[CONTENT]", article(), $file);

 

What happens is that article() just outputs its content and as this is before you print the template then it comes out at the very top of the page and then the template below it?

That's probably because your article() function echo's content out rather than storing it in a variable and returning it at the end.

 

Your article function should be something like this:

 

function article()
{
  $buff  = "Some content<br />";
  $buff .= "Some more content<br /><br />";

  return $buff;
}

Thanks, yes you're right.

I got round it by doing an ob_start() before the article is called and then doing $article = ob_get_clean() at the end but it's a bit messy. I will fix this properly soonish.

 

I always wondered why tutorials said that functions should return variables rather than echo stuff and now I know why ;)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.