Twig instanceof for inheritance objects Twig instanceof for inheritance objects symfony symfony

Twig instanceof for inheritance objects


I share the opinion, that instanceof is nothing that should appear in a template. I use twig-tests for this case

class MyTwigExtension extends TwigExtension{    public function getTests ()    {        return [            new \Twig_SimpleTest('birthday', function (Event $event) { return $event instanceof Birthday; }),            new \Twig_SimpleTest('walking', function (Event $event) { return $event instanceof Walking; })        ];    }}

And in the template

{% if event is birthday %}{# do something #}{% endif %}


An indirect way of accomplishing this would be testing the object for a method, if you know each inherited object has a unique method. Maybe your Birthday class has a getBirthday(), while your Walking class has a getMap()?

{% if yourobject.methodName is defined %}   //Stuff that should only output when the object in question has the requested method{% endif %}


Using instanceof in a template is frowned upon from an architectual standpoint. If you find yourself in a position where you "need" it, you have probably uncovered a problem in your architecture. Your getType solution in your case is probably the best. You could still put that into the event base class and read it out the name of the implementing class.