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

i use smarty V3.0 to built templates in my app.I call helper functions in templates like that:

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

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:
{assign img_props value=array('src'=>'images/img2.jpg','class'='some_class')}
{img ($img_props)}

or better:

{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?

Finally, i wrote a smarty plugin to make an associative array, in case somebody needs that:
* 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']);

     trigger_error("assoc_array: keys count not equal to values count", E_USER_NOTICE);

    for ($i=0; $i < count($keys); $i++)
        $key = $keys[$i];
        $assoc_array[$key] = $values[$i];

So now i can call within template :

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

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