本文介绍了将属性添加到树枝中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 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 计算表达式(obj 是 TestStdClass 的一个实例):
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" }更多推荐
将属性添加到树枝中的对象
发布评论