Smarty Modifier filesize

Posted on Sunday November 20, 2011 / by Eric Potvin

Smarty is a great tool when you want to separate your content and your code. Smarty comes with multiple helpful plugins but one I often use is to display how much a file takes on a hard drive.

If you fetch file information from a database and you want to display them, one of the field you want to display will be the file size. Now, if a size as more than few Megs it can be hard to read.

Here's a simple Smarty modifier that will allow you to display any given integer to a more human readable format.

Create the modifier

Create a file in the plugin directory called modifier.filesize.php and add this code:

 * Smarty plugin
 * @package Smarty
 * @subpackage PluginsModifier

 * Smarty filesize modifier plugin
 * Type:     modifier
 * Name:     filesize
 * Purpose:  show the filesize of a file in kb, mb, gb etc...
 * @param string $
 * @return string
function smarty_modifier_filesize($size)
  $size = max(0, (int)$size);
  $units = array( 'b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb');
  $power = $size > 0 ? floor(log($size, 1024)) : 0;
  return number_format($size / pow(1024, $power), 2, '.', ',') . $units[$power];

Now the only thing you have to do is add the modifier in your Smarty template: