News

Smarty 3.x Missing Template Variable error

May 5 2011

In the Smarty 3.0 release, for some odd reason the developer decided undefined variables in the template are errors. In Smarty 2.x undefined variables were treated as empty strings. This made a lot more sense to me. The whole reason I use Smarty is so I don't have to sweat details like this. 

I decided to find where in the code the error was coming from and make it work like it used to. My solution (and it may not be optimal as I didn't dig that deeply) is as follows:

1) Edit smarty/libs/sysplugins/smarty_internal_data.php and change the getVariable() function to:

    /**
     * gets the object of a Smarty variable
     * 
     * @param string $variable the name of the Smarty variable
     * @param object $_ptr optional pointer to data object
     * @param boolean $search_parents search also in parent data
     * @return object the object of the variable
     */
    public function getVariable($_variable, $_ptr = null, $search_parents = true, $error_enable = true)
    {
        if ($_ptr === null) {
            $_ptr = $this;
        } while ($_ptr !== null) {
            if (isset($_ptr->tpl_vars[$_variable])) {
                // found it, return it
                return $_ptr->tpl_vars[$_variable];
            } 
            // not found, try at parent
            if ($search_parents) {
                $_ptr = $_ptr->parent;
            } else {
                $_ptr = null;
            } 
        } 
        if (isset(Smarty::$global_tpl_vars[$_variable])) {
            // found it, return it
            return Smarty::$global_tpl_vars[$_variable];
        } 
        if ($this->smarty->error_unassigned && $error_enable) {
            throw new SmartyException('Undefined Smarty variable "' . $_variable . '"');
        } else {
			if (! $this->smarty->error_unassigned) {
            	return new Smarty_variable(null, false);
			} else {
        		if ($error_enable) {
					// force a notice
					$x = $$_variable;
        		}
            	return new Undefined_Smarty_Variable;
        	} 
        } 
    }

2) Now in your code, before calling the template, add this line:

  $smarty->error_unassigned = false; 

This assumes your instance of Smarty is called $smarty. The beauty of this method is that you don't have to turn off ALL error messages just to suppress the missing var message.

Contact

I hope you found this website useful.

Get Connected

wp-login