Re: [SMARTY] assign in included files

From: Date: Fri, 17 May 2002 19:03:48 +0000
Subject: Re: [SMARTY] assign in included files
Groups: php.smarty.general 
Request: Send a blank email to php-smarty-general+get-4287@lists.php.net to get a copy of this message
Monte, This was solved in another thread today :) Use curly braces in your quoted string to delimit the variable: <?php $a1 = array( 'a', 'b', 'c'); $a2 = array( 'a' => 'b', 'c' => 'd' ); $c = new x; class x { var $y; function x() { $this->y = 'zz'; } } print $a1[2]; print $a2['a']; print $c->y; print "<br> {$a1[2]}"; print "<br> {$a2['a']}"; print "<br> {$c->y}"; ?> Monte wrote: This is a problem that has a bit to do with how Smarty handles assigned variables. I'd like to start a discussion on this issue, it is something I've discussed with Andrei before. When you assign a template variable, it gets added to an array in the Smarty class called $_tpl_vars; this keeps track of the assigned variables. When you do this in a template: {$foo} You would _think_ that Smarty does this: <?php echo $this->_tpl_vars['foo']; ?> but it doesn't. Instead, this happens: <?php echo $foo; ?> This means that the variable $foo must be available in the local scope. To accomplish this, Smarty must extract() the assigned variables before calling the template. So any time you call display() or fetch(), smarty does an extract($this->_tpl_vars) first. That means that any time you call {assign ...} in your template, smarty will assign the variable, then _immediately_ re-extract the assigned variables again (sound like a hack?) So now to your problem: the assigned variable is not there when going back to a parent template. The problem is, when you come back out of your included template, the scope of the extraction is back to what it was before you included it. Now the ultimate question: why does Smarty extract the variables? Why not just echo $this->_tmp.var ? This reason is for the variables imbedded within quotes like so: {include file="$foo/index.tpl"} Here we imbed $foo in quotes, and the variable must be in the local scope for it to work. Can we fix it? Ideally, the variables should never be extracted, they should always come straight from $this->_tpl_vars and not have the performance overhead of extraction (actually kind of expensive!) If we wanted to do this, Smarty must parse every quoted string for variables and adjusting the syntax. Andrei can elaborate on the issues this brings up, but I would hope it is possible. For a half-baked fix, we could simply change {$foo} to this: <?php echo $this->_tpl_vars['foo']; ?> This fixes part of the issue, but doesn't fix the problem with imbedded variables... and I'm not sure if it would break anything else. Thoughts? Monte __________________________________________________ Do You Yahoo!? LAUNCH - Your Yahoo! Music Experience http://launch.yahoo.com

« previous php.smarty.general (#4287) next »