How to access class constants in Twig?

后端 未结 7 1033
醉梦人生
醉梦人生 2020-12-12 15:49

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

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

In normal PH

相关标签:
7条回答
  • 2020-12-12 16:19
    {% 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.

    0 讨论(0)
  • 2020-12-12 16:25

    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 }}
    
    0 讨论(0)
  • 2020-12-12 16:31

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

    {% if var == constant('TYPE_PERSON', entity)
    
    0 讨论(0)
  • 2020-12-12 16:32

    If you are using namespaces

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

    Important! Use double slashes, instead of single

    0 讨论(0)
  • 2020-12-12 16:38

    In book best practices of Symfony there is a section with this issue:

    Constants can be used for example in your Twig templates thanks to the constant() function:

    // src/AppBundle/Entity/Post.php
    namespace AppBundle\Entity;
    
    class Post
    {
        const NUM_ITEMS = 10;
    
       // ...
    }
    

    And use this constant in template twig:

    <p>
        Displaying the {{ constant('NUM_ITEMS', post) }} most recent results.
    </p>
    

    Here the link: http://symfony.com/doc/current/best_practices/configuration.html#constants-vs-configuration-options

    0 讨论(0)
  • 2020-12-12 16:42

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

    0 讨论(0)
提交回复
热议问题