phptaltemplate-tal

PHPTAL: graceful treatment of undefined variables


If I use a variable that hasn't been put into the scope, PHPTAL throws an exception. Is there any way of making PHPTAL fall back to graceful defaults, for example evaluating to false in a boolean context, to a blank in a string context, etc?


Solution

  • You can add "| nothing" to TALES expressions or use isset() in php: expressions.

    <p tal:attributes="class php:isset(class)?class:NULL" 
       tal:content="variable | nothing" />
    

    If you have larger bit of code that relies on a certain variable, then use exists: modifier:

    <div tal:condition="exists:variable">
    …
    </div>
    

    If you want to fake existence of any variable, it can be done, but I don't recommend it (it will hide typos):

    class FakeAll extends stdClass
    {
        function __get($var){return "";}
        function __isset($var){return true;}
    }
    
    $p = new PHPTAL();
    $p->getContext()->setGlobal(new FakeAll());