PHP Templates

Now that the fundamentals of PHP are out of the way, we can begin creating dynamic web sites. This starts with the PHP template.

A PHP template that accepts data and returns an HTML page based on that data. For example, the following is a very simple PHP template.

<?php $name = "John"; ?>

<html>
  <body>
    <h1>Hello, <?php echo $name; ?></h1>
  </body>
</html>

Notice that the variable $name is the data that we are introducing to our template. If the value of name changes the HTML is changed too. Of course, most PHP templates will be more complex than the example above. It will include conditional statements and loops to create more dynamic HTML.

In the following example, another variable, $actions, has been added, and now our template includes an if...else statement and a foreach loop. Notice how PHP can be intertwined with HTML. While this may cause some alarm, just remember that all PHP gets rendered to HTML before it is sent to the browser.

<?php 
  $name = "Ted"; 
  $actions = ["Stay here", "Go to a different page", "Leave" ]; 
?>
<html>
  <body>
    <?php if (isset($name)) : ?>
    <h1>Hello, <?php echo $name; ?>.</h1>
    <?php else : ?>
    <h1>Hello, Friend.</h1>
    <?php endif; ?>

    <h2>What do you want to do?</h2>
    <?php foreach ($actions as $action) : ?>
    <button><?php echo $action; ?></button>
    <?php endforeach; ?>
  </body>
</html>

Now that we have seen how a PHP template can be used to dynamically create HTML, next we will explore how we can make HTML more modular separating parts of our page include external files.