Is there a way to update an object\'s property in twig?
An object like the following is passed to twig:
object
property1
property2
If your property is array (object->property['key']) you can do something like this:
{% set arr = object.property|merge({"key":['some value']}) %}
{{ set(object, 'property', arr) }}
That equivalent to:
this->property['key'][] = 'some value';
I had the same problem in my knp menu template. I wanted to render an alternate field with the label
block, without duplicating it. Of course the underlying object needs an setter for the property.
{%- block nav_label -%}
{%- set oldLabel = item.label %}
{%- set navLabel = item.getExtra('nav_label')|default(oldLabel) %}
{{- item.setLabel(navLabel) ? '' : '' }}
{{- block('label') -}}
{{- item.setLabel(oldLabel) ? '' : '' }}
{%- endblock -%}
Twig has a do tag that allows you to do that.
{% do foo.setBar(value) %}
{{ set(object, 'property', value) }}
A possible way to set a property is to create a method in the object which actually creates new properties:
class Get extends StdClass
{
protected function setProperty($name,$value = null)
{
$this->$name = $value;
}
}
You can do it by merging objects:
{% set object = object|merge({'property1': 'somenewvalue'}) %}