php 更新树枝中的对象属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7719838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:14:12  来源:igfitidea点击:

Updating object properties in twig

phptwig

提问by F21

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

有没有办法在树枝中更新对象的属性?

An object like the following is passed to twig:

像下面这样的对象被传递给 twig:

object
   property1
   property2

I would like to update property1 like this:

我想像这样更新 property1:

{% 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?

上面的代码不起作用,但是可以在 twig 中做这样的事情吗?如果没有,有没有办法编写扩展或宏来做到这一点?

回答by isqua

You can do it by merging objects:

您可以通过合并对象来实现:

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

回答by New linux user

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;
    }

  }

回答by Baishu

Twig has a dotag that allows you to do that.

Twig 有一个do标签,允许你这样做。

{% do foo.setBar(value) %}

It was useful to me for forcing a menu item to be current from the template:

强制菜单项从模板中变为当前对我很有用:

{% do tertiaryNav.photos.setCurrent(true) %}

回答by Emii Khaos

I had the same problem in my knp menu template. I wanted to render an alternate field with the labelblock, without duplicating it. Of course the underlying object needs an setter for the property.

我在 knp 菜单模板中遇到了同样的问题。我想用label块渲染一个替代字段,而不是复制它。当然,底层对象需要属性的 setter。

{%- block nav_label -%}
    {%- set oldLabel = item.label %}
    {%- set navLabel = item.getExtra('nav_label')|default(oldLabel) %}
    {{- item.setLabel(navLabel) ? '' : '' }}
    {{- block('label') -}}
    {{- item.setLabel(oldLabel) ? '' : '' }}
{%- endblock -%}

回答by DarkAiR

If your property is array (object->property['key']) you can do something like this:

如果您的属性是数组 (object->property['key']),您可以执行以下操作:

{% set arr = object.property|merge({"key":['some value']}) %}
{{ set(object, 'property', arr) }}

That equivalent to:

这相当于:

this->property['key'][] = 'some value';

回答by Ros

{{ set(object, 'property', value) }}