将属性添加到树枝中的对象 [英] Adding a property to an object in twig

查看:32
本文介绍了将属性添加到树枝中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 twig 中为这个对象添加属性 2

I want to add property 2 to this object in twig

object
    property1

根据这个问题 更新树枝中的对象属性 接受的答案说它可以通过合并来实现,但是合并过滤器不适用于对象,有什么办法可以实现吗?

According to this question Updating object properties in twig The accepted answer says that it can be achieved by merge, but merge filter does not work with objects, is there any way to achieve this?

推荐答案

我认为最优雅的方法是使用 setter 和 getter:

I think the most elegant way is using setters and getters:

class TestStdClass
{
    private $prop1;

    public function getProp1()
    {
        return $this->prop1;
    }

    public function setProp1($prop1)
    {
        $this->prop1 = $prop1;
    }
}

然后在 Twig 模板中使用标签 do 计算表达式(objTestStdClass 的一个实例):

Then in a Twig template use tag do to evaluate expression (obj is an instance of TestStdClass):

{{ dump(obj) }} {# will print an empty object #}
{% do obj.setProp1('Hello') %}
{{ dump(obj) }}

这将打印:

TestStdClass {#2468 ▼
  -prop1: "Hello"
}

这篇关于将属性添加到树枝中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆