title: Simple PHP Template Class that nests templates
body: <p>I would like to build and use a super simple PHP template class.  I do not need to support any custom tags or anything.</p>
  
  <p>Just need to be able to assign variables from outside the class and then have them parsed inside of the template file.</p>
  
  <p>I then need to be able to return the parsed HTML output to a variable.</p>
  
  <p>another nice feature would be to be able to nest template files inside of one another, I have seen this a long time ago and it was super simple to accomplish.</p>
  
  <p>I do not have access to any of my old template class PHP code though so I could use any help in building a lightweight, fast and very simple class that does these tasks mentioned above.  I do not want to use an existing template system!</p>
  
  <p>In theory I believe it should work something similar to this...</p>
  
  <pre><code>//Instantiate a Template object
  $template = new Template("path/to/template.php");
  
  // Set some Template variables that can be accessed inside the template file
  $template-&gt;title = "Hello world!";
  $template-&gt;description = "This is a ridiculously simple template";
  $template-&gt;posts = array();
  
  // Return the processed template file to a variable
  $outputHtml = $template-&gt;render();
  </code></pre>
  
  <p>The template file itself might be like this...</p>
  
  <pre><code>&lt;html&gt;
      &lt;head&gt;
          // Header scripts and content
      &lt;/head&gt;
  
      &lt;body&gt;
          // Body content
          &lt;h1&gt;&lt;?php echo $this-&gt;title; ?&gt;&lt;/h1&gt;
  
          &lt;div&gt;&lt;?php echo $this-&gt;description; ?&gt;&lt;/div&gt;
  
          &lt;?php
          print_r($this-&gt;posts);
          foreach($this-&gt;posts as $key =&gt; $value){
              echo $key;
              echo '&lt;br&gt;';
              echo $key;
          }
          ?&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>And a PHP template class may look something like this....</p>
  
  <pre><code>class Template
  {
      protected $template;
      protected $variables = array();
  
      public function __construct($template)
      {
          $this-&gt;template = $template;
      }
  
      public function __get($key)
      {
          return $this-&gt;variables[$key];
      }
  
      public function __set($key, $value)
      {
          $this-&gt;variables[$key] = $value;
      }
  
      public function render()
      {
          extract($this-&gt;variables);
          chdir(dirname($this-&gt;template));
          ob_start();
  
          include basename($this-&gt;template);
  
          return ob_get_clean();
      }
  }
  </code></pre>
  
  <p>So anything I can do to improve this?  Also make nesting of templates inside of templates to work better?</p>