Updating object properties in twig
PhpTwigPhp Problem Overview
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?
Php Solutions
Solution 1 - Php
You can do it by merging objects:
{% set object = object|merge({'property1': 'somenewvalue'}) %}
Solution 2 - Php
Twig has a do tag that allows you to do that.
{% do foo.setBar(value) %}
Solution 3 - Php
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;
}
}
Solution 4 - Php
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 -%}
Solution 5 - Php
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';
Solution 6 - Php
{{ set(object, 'property', value) }}