Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access class constants in Twig?

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

{{ constant('Acme\\DemoBundle\\Entity\\Demo::MY_CONSTANT') }}

{% 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.


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

{% if var == constant('TYPE_PERSON', entity)

If you are using namespaces

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

Important! Use double slashes, instead of single


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


  • Read more about how to create and register extension in Twig documentation.
  • Read about Twig extensions in Symfony2 documentation.

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