如何在 Symfony 2 中根据对象类型的函数渲染树枝模板
我正在使用一个学说 “类表继承” 模式并有一个引用我的父类的对象。 例如:
class Pet {
protected $id;
protected $age;
}
class Dog extends Pet {
protected $ownedBones;
}
class Cat extends Pet {
protected $killedBirds;
}
class Owner {
private $pets;
}
现在我希望 twig 选择合适的模板来根据其类型的功能渲染我的儿子对象。所以猫可以有一个超级猫的 div,我的狗也可以有他们很酷的模板。 我尝试做类似的事情:
{%for pet in owner.pets%}
<div class="pet">
{{ pet }}
</div>
{%endfor%}
我得到了一个很好的结果:
致命错误:“正确类型的对象”类的对象无法转换为字符串...
所以我可能已经接近答案了? 我是 Twig 新手,所以任何帮助都会很有价值。
I am using a doctrine 'class table inheritance' pattern and have an object referencing my parrent class.
ex:
class Pet {
protected $id;
protected $age;
}
class Dog extends Pet {
protected $ownedBones;
}
class Cat extends Pet {
protected $killedBirds;
}
class Owner {
private $pets;
}
Now I would like twig to select the good template to render my son object in function of their type. So the cats can have a super catly div and my dogs can also have their cool template.
I tried to do something like that :
{%for pet in owner.pets%}
<div class="pet">
{{ pet }}
</div>
{%endfor%}
I got a nice :
Fatal Error: Object of class 'the right type of object' could not be converted to string in ...
So I might be near an answer ?
I'm kind of a Twig newbie so any help would be valued.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该在 Pet 类中添加一个抽象方法。 IE:
您应该在您的子类中实现此方法。例如:
在模板中,只需调用 render 方法:
或者您始终可以创建一个
getTemplate()
共享方法并将其包含在 twig 中:{% include pet.template %}
You should add an abstract method in the class Pet. IE:
Than in your child classes you should implement this method. For example:
In your template, just call render method:
Or else you can always create a
getTemplate()
shared method anche include it in twig:{% include pet.template %}
刚刚找到了另一种方法>不要尝试检查类型,检查属性:
Just got another way > do not try to check type, check for properties :