NYCPHP Meetup

NYPHP.org

[nycphp-talk] Templating engines

John Campbell jcampbell1 at gmail.com
Thu Jan 17 17:06:42 EST 2008


On Jan 17, 2008 10:08 AM, Yitzchak Schaffer <yitzchas at touro.edu> wrote:
>  Though I haven't heard much discussion, it seems like whenever I hear about
> templating, it's using Smarty.  Does anyone have any thoughts on
> Smarty/PHPTAL/other engines that may be out there?

I don't like PHPTAL because it only works if the output is html/xml.
A templating engine should be capable of outputting emails, csv,
javascript etc.  I like smarty, and I like plain ol' php.  Templating
is built into php, unfortunately many people don't figure out how to
use it correctly.  Below is a class that provide smarty like
templating in less than 25 lines of code:  (I haven't tested it, but
there is no reason it won't work)

<?php

Class Simple_Template {
   var $_data;

   function Simple_Template() { }

   function assign($k,$v) {
      $this->_data[$k] = $v;
      return $this;
   }
   function fetch($template) {
      ob_start();
      $this->display($template);
      return ob_get_clean();
   }
   function display($template) {
      extract($this->_data);
      include($template);
      return $this;
   }
}

// hello.php
<?php
include 'Simple_Template.php';
$tpl = new Simple_Template();
$tpl->assign('title','My First Page')->assign('message','Hello
World'); // chainability is fun
$tpl->display('view.phtml');

// view.phtml -- this is the diplay logic.
<html>
<head>
<title><?php echo $title; ?></title>
<body>
<h1><?php echo $message ?></h1>
</body>
</html>

While this looks complicated for a simple hello world application, it
cleanly separates the application logic from the display logic.  Tack
on a url router, and you can have a "framework" in less than 50 lines
of code.  It's guaranteed to be really fast too.

Regards,
John Campbell



More information about the talk mailing list