Updating object properties in twig

后端 未结 6 790
借酒劲吻你
借酒劲吻你 2020-12-29 18:30

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

An object like the following is passed to twig:

object
   property1
   property2
相关标签:
6条回答
  • 2020-12-29 18:48

    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';
    
    0 讨论(0)
  • 2020-12-29 18:50

    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 -%}
    
    0 讨论(0)
  • 2020-12-29 19:04

    Twig has a do tag that allows you to do that.

    {% do foo.setBar(value) %}
    
    0 讨论(0)
  • 2020-12-29 19:05
    {{ set(object, 'property', value) }}
    
    0 讨论(0)
  • 2020-12-29 19:07

    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;
        }
    
      }
    
    0 讨论(0)
  • 2020-12-29 19:10

    You can do it by merging objects:

    {% set object = object|merge({'property1': 'somenewvalue'}) %}
    
    0 讨论(0)
提交回复
热议问题