Creating html templates using PHP

You should check out the concepts of 'layouts' and 'view helpers'. While I've linked to the Zend Framework version of those concepts, other MVC frameworks (and the MVC concept) should have them as well.

The basic idea is that your page 'view' - for example the login form - is included into your site 'layout' - the general template that is used throughout your site. When you request a different controller, with a different view - for example a user profile - that view is also included in the same layout.

To include something like a login form on all pages, a view helper can be used. That view helper could display the current user, or display a login form, depending on the login status. View helpers may be included in the layout, or included by the specific controller (as long as MVC framework allows some kind of named render segments).

The two step 'include' method works better than linear inclusion of parts (including header, then content, then footer - what you're doing now) because your templates do not have to split HTML tags. The Zend Guide has a good visual example of view templates in a layout.


One word: Organization. Separating each part of the page will allow each of them to be viewed/edited separately. This simple concept is very beneficial. For example, anyone in the team that want to handle login process can easily figure out that they have to edit login_form.phtml and they can be sure that editing login_form.phtml will less likely to unintentionally interfere with other functionalities.

As of the best practice, here is how I do it (not exactly but similar).

$Title = 'Blah Blah Blah';
$User  = 'Jon Miller';

$ThemeName = "MyGreenPage";
$Contents  = array("User", "Login_Form");

function Include($FileName) {
    if (file_exists($FileName))
        include $FileName;
}

MyGreenPage.phtml:

<html>
  <head>
    <title><?php echo $title; ?></title>
<?php
    foreach($Contents as $Content)
        Include("$Content.pcss");
?>
<?php
    foreach($Contents as $Content)
        Include("$Content.pjs");
?>
  </head>
  <body>
<?php
    foreach($Contents as $Content)
        Include("$Content.phtml");
?>
  </body>
</html>

User.pcss:

/*  Some styles needed by User */

User.pjs:

/*  Some script needed by User */

User.phtml:

    <h3><?php echo $user; ?></h3>

Login_Form.pcss:

/*  Some styles needed by Login_Form */    

Login_Form.pjs:

/*  Some script needed by Login_Form */

Login_Form.phtml:

    <form>login form</form>

Let me remind you again that this is not that exactly what I do (what I do use OOP) so this may not exactly run as is and you may need to edit it.