Re: [SMARTY] assign template var with number of elements of an array

[email protected] (Ken Snyder) Fri, 20 Oct 2006 15:03:07 -0600
Newsgroups php.smarty.general
Message-ID <[email protected]>
Hello Nuno,

 From what I understand, developers are encouraged to assign counts 
beforehand, but I have found myself in the same situation as you.

You are correct that some functions like count can be used ***within if 
statements*** or ***as modifiers*** if they are allowed within Smarty's 
security_settings property (see 
http://smarty.php.net/manual/en/variable.security.settings.php).

I use a version of the following plugin when I need a count within a 
template. Use: {sizeof item=$banners assign=banners_count}

--Ken

<?php
// function.sizeof.php
function smarty_function_sizeof($params, &$smarty)
{
    $mixed = $params['item'];
    $assign = isset($params['assign']) ? (string)$params['assign'] : '';
   
    if( is_array($mixed) || is_object($mixed) )
        $out = count($mixed);
       
    if( $assign )
        $smarty->assign($assign,$out);
    else
        return $out;
}



Nuno Mendes wrote:
> Hi,
>
> I'm trying to create a variable inside a template (banners_count) and 
> it's value needs to be the number of elements of an array. I am using 
> this but it's not working.
>
> {assign var=banners_count value=count($banners)}
>
> How can it be done?
>
> Thanks!
>
> Nuno
>