How to access class constants in Twig?

2019-01-21 02:54发布

I have a few class constants in my entity class, e.g.:

class Entity {
    const TYPE_PERSON = 0;
    const TYPE_COMPANY = 1;
}

In normal PHP I often do if($var == Entity::TYPE_PERSON) and I would like to do this kind of stuff in Twig. Is it possible?

7条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-21 03:28

Just to save your time. If you need to access class constants under namespace, use

{{ constant('Acme\\DemoBundle\\Entity\\Demo::MY_CONSTANT') }}
查看更多
可以哭但决不认输i
3楼-- · 2019-01-21 03:30

Edit: I've found better solution, read about it here.



Let's say you have class:

namespace MyNamespace;
class MyClass
{
    const MY_CONSTANT = 'my_constant';
    const MY_CONSTANT2 = 'const2';
}

Create and register Twig extension:

class MyClassExtension extends \Twig_Extension
{
    public function getName()
    { 
        return 'my_class_extension'; 
    }

    public function getGlobals()
    {
        $class = new \ReflectionClass('MyNamespace\MyClass');
        $constants = $class->getConstants();

        return array(
            'MyClass' => $constants
        );
    }
}

Now you can use constants in Twig like:

{{ MyClass.MY_CONSTANT }}
查看更多
▲ chillily
4楼-- · 2019-01-21 03:36
{% if var == constant('Namespace\\Entity::TYPE_PERSON') %}
{# or #}
{% if var is constant('Namespace\\Entity::TYPE_PERSON') %}

See documentation for the constant function and the constant test.

查看更多
Root(大扎)
5楼-- · 2019-01-21 03:36

If you are using namespaces

{{ constant('Namespace\\Entity::TYPE_COMPANY') }}

Important! Use double slashes, instead of single

查看更多
啃猪蹄的小仙女
6楼-- · 2019-01-21 03:42

As of 1.12.1 you can read constants from object instances as well:

{% if var == constant('TYPE_PERSON', entity)
查看更多
We Are One
7楼-- · 2019-01-21 03:43

After some years I realized that my previous answer is not really so good. I have created extension that solves problem better. It's published as open source.

https://github.com/dpolac/twig-const

It defines new Twig operator # which let you access the class constant through any object of that class.

Use it like that:

{% if entity.type == entity#TYPE_PERSON %}

查看更多
登录 后发表回答