Display Tutorials

  Home arrow Display Tutorials arrow Page 8 - Writing a Template System in PHP
DISPLAY TUTORIALS

Writing a Template System in PHP
By: bluephoenix
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 69
    2004-01-13

    Table of Contents:
  • Writing a Template System in PHP
  • The Implementation
  • The Template File
  • The Class Skeleton
  • Constructor and Output
  • Replacing Tags
  • Including Dynamic Files
  • The Final Code
  • Tricks

  •  
     

    SEARCH CODEWALKERS

    Writing a Template System in PHP - The Final Code


    (Page 8 of 9 )

    Now the templating script is finished. I can store the code in a separate file and reference it when needed.

    <?php
    class Page
    {
      var 
    $page;

      function 
    Page($template "template.html") {
        if (
    file_exists($template))
          
    $this-&gt;page join(""file($template));
        else
          die(
    "Template file $template not found.");
      }

      function 
    parse($file) {
        
    ob_start();
        include(
    $file);
        
    $buffer ob_get_contents();
        
    ob_end_clean();
        return 
    $buffer;
      }

      function 
    replace_tags($tags = array()) {
        if (
    sizeof($tags) &gt0)
          foreach (
    $tags as $tag =&gt$data) {
            
    $data = (file_exists($data)) ? $this-&gt;parse($data) : $data;
            
    $this-&gt;page eregi_replace("{" $tag "}"$data,
                          
    $this-&gt;page);
            }
        else
          die(
    "No tags designated for replacement.");
      }

      function 
    output() {
        echo 
    $this-&gt;page;
      }
    }
    ?>

    After initializing the object with the name of the HTML template file, pass an array of place holders found within the template and the data files or information to the replace_tags method and use the output method to flush the processed page from the class to standard output.

    <?php
    require_once("lib/template.php");

    $page = new Page("template.html");

    $page-&gt;replace_tags(array(
      
    "title" =&gt"HOME",
      
    "descript" =&gt"Welcome to my website!",
      
    "main" =&gt"dat/index.dat",
      
    "menu" =&gt"dat/menu.dat",
      
    "left" =&gt"dat/submenu.dat",
      
    "right" =&gt"dat/right.dat",
      
    "footer" =&gt"dat/footer.php"
    ));

    $page-&gt;output();
    ?>

    More Display Tutorials Articles
    More By bluephoenix

    blog comments powered by Disqus

    DISPLAY TUTORIALS ARTICLES

    - Smart Auto Refresh
    - Writing a Template System in PHP

    Developer Shed Affiliates

     



    © 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap