how can we get the class name of the entity object in the twig view

advertisements

For a example, if we pass a table object to the twig view, how can we get the class name of that object like 'Table'.

class Table{

}

$table = new Table();

In Twig:

{{ table.className }} ---> this should display 'Table'


If you don't want to make this a method on the entity like so:

public function getClassName()
{
    return (new \ReflectionClass($this))->getShortName();
}

then you could create a Twig function or filter. Here's a function:

class ClassTwigExtension extends \Twig_Extension
{
    public function getFunctions()
    {
        return array(
            'class' => new \Twig_SimpleFunction('class', array($this, 'getClass'))
        );
    }

    public function getName()
    {
        return 'class_twig_extension';
    }

    public function getClass($object)
    {
        return (new \ReflectionClass($object))->getShortName();
    }
}

Use like so:

{{ class(table) }}