Migrating from Smarty to Flexy

15:54 on Tue 2007-03-20 by Leons Petrazickis PHP

Templates are a great way to separate business logic from page layout in web applications. Smarty (LGPL) and Flexy (PHP License) are two great, mature templating libraries for PHP. Flexy is the younger and faster of two, so there is a tendency to migrate installed Smarty implementations onto it.

Migrating the PHP

Engine Declaration

Smarty:

$smarty = new Smarty();

Flexy:

$smarty = new HTML_Template_Flexy_SmartyAPI();

This API is largely limited to emulating the assign() method.

Engine Configuration

Smarty:

$smarty->template_dir = ‘./smarty/templates’;
$smarty->compile_dir = ‘./smarty/templates_c’;
$smarty->cache_dir = ‘./smarty/cache’;
$smarty->config_dir = ‘./smarty/config’;

Flexy:

$options = array();
$options[‘templateDir’][] = dirname(__FILE__) . \\flexy\templates’;
$options[‘compileDir’] = dirname(__FILE__) . \\flexy\templates_c’;

Your templates go into the templateDir. Flexy will compile them to optimized PHP code and cache it in compileDir.

Page Display

Smarty:

$smarty->display($template);

Flexy:

$object = new StdClass;
foreach($smarty->vars as $k=>$v) {
  $object->$k = $v;
}

$flexy = new HTML_Template_Flexy($options);
$flexy->compile($template);
$flexy->outputObject($object, array());

Needless to say, this code would be much simpler if you were writing a web app from scratch. The goal during migration is to minimize points of change, which is achieved by slightly baroque markup at selected points rather than elegant markup across the board.

Migrating the Templates

Unfortunately, Flexy’s syntax differs from that of Smarty. I would recommend doing a search-and-replace with regular expressions across all your templates. On Windows, UltraEdit offers this across multiple files. On Unix, a script could be readily written.

Variables

Smarty:

{$blurb}

Flexy:

{blurb:h}
{blurb} // escaped HTML
{blurb:u} // URL-encoded

Unlike Smarty, Flexy escapes HTML tags by default. It’s arguably more secure, but I find that I need to insert raw HTML into a template fairly often.

Array Loops

Smarty:

{section name=t loop=$tables}
  <li>{$tables[t]}</li>
{/section}

Flexy:

{foreach:tables,key,value}
  <li>{value:h}</li>
{end:}

Lower-case t should be avoided as a variable name in Flexy.

Javascript Variables

Smarty:

<script type="text/javascript">
  var db = ‘{$db}’;
</script>

Flexy:

<flexy:toJavascript db="db">

This is a useful way to transfer a variable from PHP to your client-side Javascript. It comes especially handy with Javascript strings.

Includes

Smarty:

{include file=’0top.tpl’}

Flexy:

<flexy:include src="0top.tpl">

Documentation

Flexy Home
Flexy Documentation

This covers the minimum needed to migrate from Smarty to Flexy. I highly recommend abstracting and encapsulating some of these operations for ease of maintenance. It’s best to avoid repeating yourself.