只是为了节省您的时间。如果您需要访问命名空间下的类常量,请使用
{{ constant('Acme\\DemoBundle\\Entity\\Demo::MY_CONSTANT') }}
{% if var == constant('Namespace\\Entity::TYPE_PERSON') %}
{# or #}
{% if var is constant('Namespace\\Entity::TYPE_PERSON') %}
请参阅 constant
function 和 constant
test 的文档。
{% if var is constant('TYPE_PERSON', object) %}
从 1.12.1 开始,您也可以从对象实例中读取常量:
{% if var == constant('TYPE_PERSON', entity)
{{ constant('Namespace\\Classname::CONSTANT_NAME') }}
(doc)
{{ constant('TYPE_PERSON', entity) }}
一样使用它,则可以执行以下操作(实例化实体类)$this->render('index.html.twig', ['entity' => new Entity()]);
constant('SOME_CONSTANT', form.getFoo())
,其中 getFoo()
返回自定义 FormType PHP 类。
如果您使用命名空间
{{ constant('Namespace\\Entity::TYPE_COMPANY') }}
重要的!使用双斜杠,而不是单斜杠
编辑:我找到了更好的解决方案,read about it here.
在 Twig 文档中阅读有关如何创建和注册扩展的更多信息。
阅读 Symfony2 文档中的 Twig 扩展。
假设你有课:
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 }}
constant()
与 FQN 一起使用会很麻烦。
在 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 %}
User#TYPE_PERSON
,可以将 NodeExpression
类更改为这样的名称,这对我有用:->raw('(constant(\'App\\Entity\\' . $this->getNode('left')->getAttribute('name') . '::' . $this->getNode('right')->getAttribute('name') . '\'))')
。当然,这会将您的类限制为 App\Entity
命名空间,但我认为这涵盖了最常见的用例。
不定期副业成功案例分享
{% if var == object.MY_CONSTANT %}