更新树枝中的对象属性
有没有办法更新树枝中对象的属性?
像下面这样的对象被传递给 twig:
object
property1
property2
我想像这样更新 property1:
{% set object.property1 = 'somenewvalue' %}
上面的代码不起作用,但是可以在 twig 中做这样的事情吗?如果没有,有没有办法编写扩展或宏来做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
2013 年的答案
您可以通过合并对象来实现:
2023 年的更新
我不知道该解决方案从哪个版本的 twig 不再起作用。现在你只能创建一个具有新名称的对象:
Answer from 2013
You can do it by merging objects:
Update from 2023
I don’t know from which version of twig this solution does not work anymore. Now you can only create an object with a new name:
Twig 有一个 do 标签,允许您执行此操作。
Twig has a do tag that allows you to do that.
设置属性的一种可能方法是在对象中创建一个实际创建新属性的方法:
A possible way to set a property is to create a method in the object which actually creates new properties:
我的 knp 菜单模板中遇到了同样的问题。我想用
label
块渲染一个备用字段,而不重复它。当然,底层对象需要属性的设置器。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.如果您的属性是数组 (object->property['key']) 您可以执行以下操作:
相当于:
If your property is array (object->property['key']) you can do something like this:
That equivalent to: