簡體   English   中英

如何訪問Twig中的類常量?

[英]How to access class constants in Twig?

我的實體類中有一些類常量,例如:

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

在普通的PHP中,我經常做if($var == Entity::TYPE_PERSON) ,我想在Twig中做這種事情。 可能嗎?

只是為了節省你的時間。 如果需要訪問命名空間下的類常量,請使用

{{ constant('Acme\\DemoBundle\\Entity\\Demo::MY_CONSTANT') }}
{% if var == constant('Namespace\\Entity::TYPE_PERSON') %}
{# or #}
{% if var is constant('Namespace\\Entity::TYPE_PERSON') %}

請參閱constant函數constant測試的文檔。

從1.12.1開始,您也可以從對象實例中讀取常量:

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

如果您使用名稱空間

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

重要! 使用雙斜杠,而不是單斜杠

編輯:我找到了更好的解決方案, 請在此處閱讀。



假設你上課了:

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

創建並注冊Twig擴展:

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

現在你可以在Twig中使用常量了:

{{ MyClass.MY_CONSTANT }}

在Symfony的書籍最佳實踐中,有一個部分涉及此問題:

由於constant()函數,常量可以在Twig模板中使用:

// src/AppBundle/Entity/Post.php
namespace AppBundle\Entity;

class Post
{
    const NUM_ITEMS = 10;

   // ...
}

並在模板樹枝中使用此常量:

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

鏈接: http//symfony.com/doc/current/best_practices/configuration.html#constants-vs-configuration-options

幾年后,我意識到我以前的答案並不是那么好。 我創建了擴展,可以更好地解決問題。 它是作為開源發布的。

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

它定義了新的Twig運算符# ,它允許您通過該類的任何對象訪問類常量。

像這樣使用它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM