Smarty’s hidden global variables

Recently I have been working on some web design projects in which we are using the templating parser Smarty. And even though the parser itself is very extensive, the documentation is not. To use variables across nested template files you need to globalise variables. I wrote a tiny Smarty plugin that does this job for you.

I stumbled upon a problem in the new 3.x version. I couldn’t get certain variables to work from one of the plugins I wrote for it. After some searching I managed to work it out that it wasn’t a problem of my plugin, but that it wasn’t possible to set a variable in one template file and use it in another (nested) template file. It turned out that when you assign variables they are not assigned globally but only for the current template file. So how to set those variables globally then?

Well you can use the {assign var="varName" value="varValue" scope="global"} tag, but in case of a ph written plugin that is not very convenient. So the undocumented equivalent php method is simply assignGlobal(), and works the same as assign().

So for example:

function smarty_block_insertInHead($params, $content, $template, &$repeat)
   * your code
   $template->assignGlobal('headInsert', $content);

In the new 3.x version template files can now also be extended. Yes, as in OOP!. This might in most cases a neater solution to get variables or blocks of code across “nested” templates as it provides a nicer fall back for undefined variables.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.