I want to add property 2 to this object in twig
object
property1
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?
You could also add a general setter to your class to get the dynamicity like in Kison's solution:
And then in Twig:
This is simpler than Kison's solution and more dynamic than martin's solution. However, if you have many classes that need this kind of general setter, then Kison's solution might be better as it's more universal (i.e. you can add properties to objects of any class).
Don`t know about standart way to do it in twig, but i think that you can do it like this:
1. Create custum twig extension
2. Add extension to your twig renderer
3. Use function in your twig template
Notice: Not tested
I think the most elegant way is using setters and getters:
Then in a Twig template use tag
do
to evaluate expression (obj
is an instance ofTestStdClass
):This will print: