How to render a twig template in function of the object type in Symfony 2

StackOverflow https://stackoverflow.com/questions/8880690

  •  28-10-2019
  •  | 
  •  

Pergunta

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.

Foi útil?

Solução

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 %}

Outras dicas

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 %}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top