madhur madhur - 1 year ago 84
Twig Question

Adding a property to an object in twig

I want to add property 2 to this object in twig


According to this question Updating object properties in twig The accepted answer says that it can be achieved by merge, but merge filter does not work with objects, is there any way to achieve this?

Answer Source

I think the most elegant way is using setters and getters:

class TestStdClass
    private $prop1;

    public function getProp1()
        return $this->prop1;

    public function setProp1($prop1)
        $this->prop1 = $prop1;

Then in a Twig template use tag do to evaluate expression (obj is an instance of TestStdClass):

{{ dump(obj) }} {# will print an empty object #}
{% do obj.setProp1('Hello') %}
{{ dump(obj) }}

This will print:

TestStdClass {#2468 ▼
  -prop1: "Hello"