Variable Variable in Smarty Templates

百般思念 提交于 2019-12-13 06:23:54

问题


I have a dynamically generated Smarty variable in PHP. I want to access it with name ,

Say for example there is a smarty variable {$asdf} which was generated dynamically and i have an array that has 'asdf' i want to use this array and access {$asdf}.

{$asdf} prints a input element [rendered] ;  
 $array = array('asdf');
{foreach from=$array item=x}
       {$x} 
{/foreach}

//but {$x} is not giving renderend input instead it is giving $asdf

where am i going wrong?


回答1:


It is generally atypical to do this type of work in a template file. You should separate your template and logic as much as possible -- there's no plausible scenario in which you could not simply prepare the needed variables for your template in php and pass them on to the template in a useable structure.

That said, it is possible. Within a template, all variables that were passed to the template are accessible in an array, Smarty::_tpl_vars. Within a template, one may interact with this array using the {php}{/php} tags, where it can be referenced via $this --

{php}
    $unknownValue = $this->_tpl_vars[
        $this->_tpl_vars['known_key']
    ];
    // for example...
    $this->_tpl_vars['magicalValue'] = $unknownValue;
{/php}
Magic: {$magicalValue}

I cannot reiterate enough, however, that it is generally bad practice to place such logic inside a template.



来源:https://stackoverflow.com/questions/19962650/variable-variable-in-smarty-templates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!