Search code examples
phpsmartydynamic-variables

Dynamic variable names in Smarty


I want to be access some variables I've assigned dynamically from PHP in Smarty, here is an example:

$content_name = 'body'
$smarty->assign('content_name',$content_name);
$smarty->assign($content_name.'_title',$title);
$smarty->assign($content_name.'_body',$body);

// assigned values
// $content_name = home
// $home_title = $title
// $home_body = $body

The reason I want to access these dynamically is because I call multiple versions of a function that includes the code above, they all use the same template and therefore don't want to simply use $title, $body etc as their valus will conflict with each other.

Given that I know I want to access the title and body variables based on the content_name I set, how can I achieved this within smarty?


Solution

  • As per my comment on using an array instead of dynamic variables, here's an example of how to add the vars to an array:

    php:

    $vars = array();
    
    function whatever() {
        global $vars;
    
    
        $vars[] = array(
            'firstname' => 'Mike',
            'surname' => 'Smith'
        );
    }
    
    $smarty->assign('vars', $vars);
    

    smarty:

    {section name=loop loop=$vars}
        Name: {$vars[loop].firstname} {$vars[loop].surname}
    {/section}