Smarty Modifier filesize

狂风中的少年 提交于 2019-12-09 08:11:07

问题


I am using Smarty and one of my section shows file names, including dates, file size, last access etc...

I want to display the size of the file in K if less then 1024, in Mb if less than 1048576 etc...

The data (file info) comes from the database (name, file size, date etc...)

ex:

File             Mime       Size       Date 
Filename1.jpg    mime/jpg   14.1Kb     2011/12/12

Is there any modifier in Smarty that do this?

Thanks


回答1:


create a file in the plugin directory called: modifier.filesize.php

then add this code:

<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage PluginsModifier
*/

/**
 * Smarty replace modifier plugin
 * 
 * Type:     modifier<br>
 * Name:     filesize<br>
 * 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];
} 
?>

then you can use: {$filename.size|filesize}




回答2:


assuming the size you are giving is originally in bytes,

try this:

{if $size lt 1024}
  {$size} bytes
{elseif $size lt 1048576}
  {$size / 1024}Kb
{else}
...
{/if}


来源:https://stackoverflow.com/questions/8185828/smarty-modifier-filesize

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!