entens.net The less one forgets, the less one can remember.

Basic PHP Templating System for HTML

The class:

  1. <?
  2. class Template {
  3.    public $template;
  4.    function load($filepath) {
  5.       $this->template = file_get_contents($filepath);
  6.    }
  7.    function replace($var, $content) {
  8.       $this->template = str_replace("#$var#", $content, $this->template);
  9.    }
  10.    function publish() {
  11.          eval("?>".$this->template."<?");
  12.    }
  13. }
  14. ?>

The template (layout.html):

  1. <html>
  2. <head>
  3. <title>#title#</title>
  4. </head>
  5. <body>
  6. <h3>Hello #name#!</h3>
  7. <p>The time is: #datetime#</p>
  8. <? echo "<p>Embedded PHP works too!</p>"; ?>
  9. </body>
  10. </html>

use example:

  1. <?
  2. include "template.class.php";
  3.  
  4. $template = new Template;
  5. $template->load("design.html");
  6. $template->replace("title", "My Template Class");
  7. $template->replace("name", "William");
  8. $template->replace("datetime", date("m/d/y"));
  9. $template->publish();
  10. ?>
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.