Welcome Guest, Not a member yet? Register   Sign In
Pass array parameter in helper function within smarty template
#1

[eluser]Unknown[/eluser]
Hello,
i use smarty V3.0 to built templates in my app.I call helper functions in templates like that:
Code:
{helper_fun(func_parameter_1,func_parameter_2,..)}

In some helper functions is needed to pass a properties associative array as parameter.
e.g img function in html_helper :
Code:
$img_props = array(
          'src' => 'images/picture.jpg',
          'class' => 'img_class'.);
img($img_props);


I really don't want to define the properties array in my controller, then assign it to template and make the call like : {img($img_props)}

So, i'm looking for a way to define an associative array withing template, so i can do something like:
Code:
{assign img_props value=array('src'=>'images/img2.jpg','class'='some_class')}
{img ($img_props)}

or better:
Code:
{img(array('src'=>'images/img2.jpg','class'='some_class'))}

or:
Code:
{img src='images/img2.jpg' class='some_class'}

I know that i can use smarty's html_image, but img is just an example.
It's a general problem.

Do you have an opinion on that?
#2

[eluser]Unknown[/eluser]
Finally, i wrote a smarty plugin to make an associative array, in case somebody needs that:
Code:
/**
* Smarty {assoc_array(} function plugin
*
* Type:     function<br>
* Name:     assoc_array(<br>
* Date:     Feb 13, 2011<br>
* Purpose:  assigns an associative array  var from two strings (keys,values)<br>
* Examples: {assoc_array keys='key1,key2' values='value1,value2' assign=assocarray }
* Output:   assigns in template var $assocarray = Array ('key1'=>'value1','key2'=>value2)
* @author [email protected]
*/

function smarty_function_assoc_array($params,$template)
{
    $assoc_array = Array();

    $keys = explode(",",$params['keys']);
    $values = explode(",",$params['values']);

    if(count($keys)!=count($values))
    {
     trigger_error("assoc_array: keys count not equal to values count", E_USER_NOTICE);
     return;
    }

    for ($i=0; $i < count($keys); $i++)
    {
        $key = $keys[$i];
        $assoc_array[$key] = $values[$i];
    }        
        
    $template->assign($params['assign'],$assoc_array);        
}

So now i can call within template :

Code:
{assoc_array  keys='src,alt,title'  values={cms_image_url()}|cat:'/admin_logo.jpg,somealt,sometitle' assign='img_props'}
{img($img_props)}
#3

[eluser]mohrt[/eluser]
With Smarty 3 this is possible:

{$foo = ['bar'=>'baz','bar2'=>$blah,'bar3' => ['a'=>'b']]}

Array building is often left to PHP though, as it should Smile




Theme © iAndrew 2016 - Forum software by © MyBB