Search code examples
phptwig

Updating object properties in twig


Is there a way to update an object's property in twig?

An object like the following is passed to twig:

object
   property1
   property2

I would like to update property1 like this:

{% set object.property1 = 'somenewvalue' %}

The above code does not work, but is it possible to do something like this in twig? If not, is there a way to write an extension or macro to do this?


Solution

  • Answer from 2013

    You can do it by merging objects:

    {% set object = object|merge({'property1': 'somenewvalue'}) %}
    

    Update from 2023

    I don’t know from which version of twig this solution does not work anymore. Now you can only create an object with a new name:

    {% set data = {foo:1} %}
    {% set updated = data|merge({ bar: 2 }) %}
    
    foo: {{ updated.foo }} {# Produces “foo: 1” #}
    bar: {{ updated.bar }} {# Produces “bar: 2” #}