Get all variables assigned to Smarty - Part 2Get all variables assigned to Smarty - Part 2

Posted November 23rd, 2009 in PHP

A few weeks back I posted how to get all the variables assigned to Smarty using the get_template_vars() function and in this post expand the example and show how to get just one assigned variable instead of everything.

Assigning variables

Variables are assigned to Smarty using the ->assign function like so:

$smarty->assign('first_name', 'Chris');
$smarty->assign('last_name', 'Hope');
$smarty->assign('interests', array('reading', 'movies', 'tv', 'running'));

Listing all variables

When assembling all the variables for a template you may have dozens of variables consisting of single values (strings, integers, dates etc) as well as arrays and other variables.

As covered in my earlier post you can get a complete list of all the variables using the get_template_vars() function and either returning it as an array and accessing the values from there, or dumping it to standard output for debugging purposes using print_r, var_dump or similar.

However, if you have a lot of data assigned to Smarty and don't want to dump the whole lot into an array, pass the optional parameter to specify which variable you want to return.

Using the above assignments, to just dump the 'interests' variable using print_r() do this:

print_r( $smarty->get_template_vars('interests') );

Using the above example this would output this:

Array
(
    [0] => reading
    [1] => movies
    [2] => tv
    [3] => running
)

Related posts:

Comments

blog comments powered by Disqus