我们如何在树枝视图中获取实体对象的类名 [英] how can we get class name of the entity object in twig view

查看:28
本文介绍了我们如何在树枝视图中获取实体对象的类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举个例子,如果我们将一个 table 对象传递给 twig 视图,我们如何获得该对象的类名,如Table".

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();

在树枝中:

{{ table.className }} ---> 这应该显示 'Table'

{{ 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();
}

然后你可以创建一个 Twig 函数或过滤器.这是一个函数:

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

像这样使用:

{{ class(table) }}

这篇关于我们如何在树枝视图中获取实体对象的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆