PHP Tutorial

Step 4

PHP Tutorial

In this tutorial we will create a simple twitter copycat. In step 4 we will organize our template code.

Step 4

1. In the last step we created our first template: tweets/list.tpl:

<!DOCTYPE html>
<html>
  <head>
    <title>Twitter Example</title>
    <meta charset='utf-8'>
    <link rel="stylesheet" href="{$BASE_URL}/css/style.css">
  </head>
  <body>

    <section id="tweets">
        <h2>Tweets</h2>

      {foreach $tweets as $tweet}

      <article class="tweet-data">
        <span class="realname">{$tweet.realname}</span>
        <a href="#" class="username">@{$tweet.username}</a>
        <span class="time">{$tweet.time}</span>
        <div class="tweet-text">{$tweet.text}</div>
      </article>

      {/foreach}

    </section>

  </body>
</html>

As we can see, there is a part of this template that is actually responsible for listing the tweets while the remaining is just generic code that will be repeated throughout the site.


2. In order to promote code reuse, even at the template level, we will separate this code into 3 parts: the actual tweet list, an header and a footer.

We will save the header in the templates folder under common/header.tpl:

<!DOCTYPE html>
<html>
  <head>
    <title>Twitter Example</title>
    <meta charset='utf-8'>
    <link rel="stylesheet" href="{$BASE_URL}/css/style.css">
  </head>
  <body>

And the footer as common/footer.tpl:

  </body>
</html>

We will then include those two files inside the tweets/list.tpl template:

{include file='common/header.tpl'}

<section id="tweets">
  <h2>Tweets</h2>

  {foreach $tweets as $tweet}

  <article class="tweet-data">
    <span class="realname">{$tweet.realname}</span>
    <a href="#" class="username">@{$tweet.username}</a>
    <span class="time">{$tweet.time}</span>
    <div class="tweet-text">{$tweet.text}</div>
  </article>

  {/foreach}

</section>

{include file='common/footer.tpl'}

In step 5 we will create a new page that lists tweets from one user only.