NYCPHP Meetup

NYPHP.org

[nycphp-talk] To Smarty Or Not to Smarty: That Is The Question

Tim Lieberman tim_lists at o2group.com
Wed Sep 6 03:03:40 EDT 2006


Mikko Rantalainen wrote:

>The only thing you need to change for different rendering of the 
>above data is to set $class variable to another value. I don't 
>understand how many different ways there could be to encode that 
>same information in XHTML. Therefore, I don't understand the need 
>for templating engine to generate/modify that part of the source. To 
>me, the only question is what solution has the best performance? A 
>template engine is seldom the correct answer.
>  
>
I use Smarty extensively, but mostly as part of my ad-hoc framwork for
rapid development, along with DB_DataObject. 

I wrote a little subclass of PEAR's DB_DataObject that I call
DB_DataObject_renderable

The subclass provides two new methods to DataObject: 
render($tpl,$extra=array) and renderlist($tpl,$extra=array).

render() (sometimes) pulls in related table via getLink() or getLinks(),
assigns object variables, plus the contents of the $extra hash, into
smarty, and then returns the result of Smarty->fetch($tpl).

renderlist() iterates over $this->fetch() (where this is essentially a
DB_DataObject), concatinating the result of
$this->render($tpl."_listitem.tpl") into a string, then passes that as
$extra['listContent'] into $this->render($tpl.".tpl"). 

Keeping with DB_DataObject's convention of an object being both a
"current record" and a "record set", and with all the handy getLinks
stuff, which is nice for pulling in lookup-table stuff, you have a nice
way of rendering either a record or set of them.

For clarity's sake, if I want to show a form, I might have a template
called "form.tpl".  If I want a table of records, I might have a
template called 'adminlist.tpl', and one called 'adminlist_listitem.tpl'. 

'adminlist_listitem.tpl' might look like:

<tr><td>{$id}</td><td>{$name}</td><td><a
href="edit.php?id={$id}">edit</a></td></tr>

'adminlist.tpl' might look like:

<table class="someClass">
<tr><th>ID</th><th>Name</th><th>*</th></tr>
{$listContent}
</table>

While this example is trivial, the pattern scales well to various
things.  And if you need even more "extra" data, it's easy to override
the render() function in the class files autogenerated by DB_DataObject
to pull in the ... weird ... stuff.

-Tim




More information about the talk mailing list