译者:taowen
In general, template engines are a "good thing." 总体来说,模板引擎是一个"好东西"
作为一个PHP/Perl的程序员,许多模板引擎(fastTemplate, Smarty, Perl的 HTML::Template)的用户,以及我自己的bTemplate [1]的作者,我讲这句话很多次了。
然而,在同事进行了长时间的讨论之后,我确信了大量的模板引擎(包括我自己写的)根本是错误的。 我想唯一的例外是Smarty [2],虽然我认为它太庞大了,并且考虑到这篇文章的其余部分相当的没有观点。然而,就你为什么选择Smarty(或者类似的解决方案)有几个理由,这些将在文章后面探究。
这篇文章讨论模板的理论。我们将看到为什么大部分"模板引擎"是过于肥大,并且最终我们将回过头来看一个轻量级的,小巧快速的另类选择。
下载和授权
模板类和所有在本文中使用的例子能够在这里下载:template.zip [3]。你可以根据发布 [4]在OSI [5]的MIT Open Source License使用这些文件中的代码。
/** * This variable holds the file system path to all our template files. */ $path = './templates/';
/** * Create a template object for the outer template and set its variables. */ $tpl = & new Template($path); $tpl->set('title', 'User List');
/** * Create a template object for the inner template and set its variables. The * fetch_user_list() function simply returns an array of users. */ $body = & new Template($path); $body->set('user_list', fetch_user_list());
/** * Set the fetched template of the inner template to the 'body' variable in * the outer template. */ $tpl->set('body', $body->fetch('user_list.tpl.php'));