A Smarty templates object array example

Smarty templates object array FAQ: How can I display an array of objects with Smarty templates?

I just wasted about thirty minutes trying to figure out how to display an array of objects with Smarty templates, so I thought I'd share the solution here. I'll include my PHP class, some of the PHP logic that builds the Smarty variables (my Smarty object array), and then a portion of the Smarty template that displays my PHP object array.

1) My PHP class

First, I have this PHP class that I use to represent a certain type of file I've defined:

<?php
class CodemeFile
{
  var $id;
  var $directory_id;
  var $filename;

  function CodemeFile($id, $directory_id, $filename)
  {
    $this->id = $id;
    $this->directory_id = $directory_id;
    $this->filename = $filename;
  }
}
?>

(That's just a subset of what the class does, which is all you need to see for this example.)

2) Building my Smarty template variables

Next up, I create my Smarty template variables in my PHP controller class. To be more clear, I create the array of objects I want Smarty to display, and then I display the Smarty template named directory.tpl:

# get a list of files (CodemeFile type) at this dir level
$files = $this->get_files_for_dir($dir_id);

# forward my object array on to the template
$smarty->assign('files', $files);
$smarty->display('directory.tpl');

In this code, the variable "$files" is actually an array of files that exist in a certain directory.

(Note that there is a Smarty assign_by_reference method, and I'm not sure if I should use that here or not. I'll experiment with this shortly.)

3) The Smarty template to display the PHP object array

Last up in this formula is the source code the for the Smarty template that displays my PHP object array. Skipping all the other HTML, here's the Smarty template section where I display the output of my object array:

{section name=filesec loop=$files}
{assign var=file value=$files[filesec]}
{$file->id}
{$file->directory_id}
{$file->filename}
{/section}

I'm not showing any fancy HTML formatting; you can format the output however you want. I just wanted to show you how to access a PHP object array in a Smarty template, and I know this code just worked on my project.

This should be all you need to display an array of objects in a Smarty template. If anyone knows how to do this better, please leave a comment in the Comments section below, but for now, I can tell you that this Smarty object array approach just worked in my project.