如何在 Symfony 2 中根据对象类型的函数渲染树枝模板

发布于 2024-12-27 15:00:35 字数 756 浏览 1 评论 0原文

我正在使用一个学说 “类表继承” 模式并有一个引用我的父类的对象。 例如:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

记忆消瘦 2025-01-03 15:00:35

您应该在 Pet 类中添加一个抽象方法。 IE:

class Pet
{
    abstract function render();
}

您应该在您的子类中实现此方法。例如:

class Dog extends Pet
{
    public function render()
    {
        return sprintf('<div class="dog">%s</div>', 'blabla');
    }
}

在模板中,只需调用 render 方法:

{{ pet.render() }}

或者您始终可以创建一个 getTemplate() 共享方法并将其包含在 twig 中:{% include pet.template %}

You should add an abstract method in the class Pet. IE:

class Pet
{
    abstract function render();
}

Than in your child classes you should implement this method. For example:

class Dog extends Pet
{
    public function render()
    {
        return sprintf('<div class="dog">%s</div>', 'blabla');
    }
}

In your template, just call render method:

{{ pet.render() }}

Or else you can always create a getTemplate() shared method anche include it in twig: {% include pet.template %}

猫性小仙女 2025-01-03 15:00:35

刚刚找到了另一种方法>不要尝试检查类型,检查属性:

{% if pet.ownedBones is defined %}
woot that's a dog
{% else %}
it's somthing else
{% endif %}

Just got another way > do not try to check type, check for properties :

{% if pet.ownedBones is defined %}
woot that's a dog
{% else %}
it's somthing else
{% endif %}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文