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?
Just to save your time. If you need to access class constants under namespace, use
Edit: I've found better solution, read about it here.
Let's say you have class:
Create and register Twig extension:
Now you can use constants in Twig like:
See documentation for the
constant
function and theconstant
test.If you are using namespaces
Important! Use double slashes, instead of single
As of 1.12.1 you can read constants from object instances as well:
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 %}