how can we get class name of the entity object in

2019-02-06 00:10发布

问题:

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'

回答1:

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


回答2:

In \Twig_Extension you can add tests

public function getTests()
{
    return [
        'instanceof' =>  new \Twig_Function_Method($this, 'isInstanceof')
    ];
}

/**
 * @param $var
 * @param $instance
 * @return bool
 */
public function isInstanceof($var, $instance) {
    return  $var instanceof $instance;
}

And then use like

{% if value is instanceof('DateTime') %}


标签: symfony twig