Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig template engine not reading object properties

Twig lets you pass array or object to the template and gives you the same interface to access members for both data structures. So, for example:

$test = array('foo' => 'foo', 'bar' => 'bar');

Will let you access this in template as test.foo and test.bar

Now instance of this object will have the same effect. Which is very awesome :)

class test
{
    public $foo;
    public $bar;
}

How about an object that uses magic __set and __get methods?

class test
{
    public $properties;

    public function __set($name, $value)
    {
        $this->properties[$name] = $value;
    }

    public function __get($name)
    {
        return $this->properties[$name];
    }
}

Unfortunately in this case you can't access properties of this object. I'm not sure if the Twig is the issue here or PHP itself.

like image 283
marcin_koss Avatar asked Jan 08 '13 05:01

marcin_koss


People also ask

Is Twig a template engine?

Twig is a modern template engine for PHPSecure: Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.

What is block in Twig?

Blocks are used for inheritance and act as placeholders and replacements at the same time. They are documented in detail in the documentation for the extends tag. Block names must consist of alphanumeric characters, and underscores. The first char can't be a digit and dashes are not permitted.


1 Answers

You need to implement __isset() as well, eg

public function __isset($name) {
    return array_key_exists($name, $this->properties);
}

See http://twig.sensiolabs.org/doc/recipes.html#using-dynamic-object-properties

like image 194
Phil Avatar answered Nov 03 '22 11:11

Phil