Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all assigned Smarty variables while running the template?

Tags:

php

smarty

I would like to get all variables assigned to Smarty inside the template. For example, if I have this code

$smarty->assign('name', 'Fulano');
$smarty->assign('age', '22');
$result = $this->smarty->fetch("file:my.tpl");

I would like to have a my.tpl like the one below:

{foreach from=$magic_array_of_variables key=varname item=varvalue}
{$varname} is {$varvalue}
{/foreach}

such as the content of result would be

name is Fulano
age is 22

So, is there a way to get this $magic_array_of_variables?

like image 533
brandizzi Avatar asked Aug 03 '12 16:08

brandizzi


1 Answers

all code below is smarty2

All smarty variables are held inside the $smarty->_tpl_vars object, so before fetching() your template, you could do:

$smarty->assign('magic_array_of_variables', $smarty->_tpl_vars);

Since this may be impractical, you could also write a small smarty plugin function that does something similar:

function smarty_function_magic_array_of_variables($params, &$smarty) {
    foreach($smarty->_tpl_vars as $key=>$value) {
        echo "$key is $value<br>";
    }
}

and from your tpl call it with:

{magic_array_of_variables}

Alternatively, in this function you can do:

function smarty_function_magic_array_of_variables($params, &$smarty) {
    $smarty->_tpl_vars['magic_array_of_variables'] =  $smarty->_tpl_vars;
}

and in your template:

{magic_array_of_variables}
{foreach from=$magic_array_of_variables key=varname item=varvalue}
{$varname} is {$varvalue}
{/foreach}
like image 61
periklis Avatar answered Nov 14 '22 21:11

periklis