【发布时间】:2011-11-28 11:49:06
【问题描述】:
我的实体类中有一些类常量,例如:
class Entity {
const TYPE_PERSON = 0;
const TYPE_COMPANY = 1;
}
在普通的 PHP 中,我经常使用if($var == Entity::TYPE_PERSON),我想在 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 == object.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.
假设你有课:
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 命名空间,但我认为这涵盖了最常见的用例。