jdecool/twig-constant-accessor-bundle

简化在 Twig 中访问类常量的方式

1.10.0 2024-05-02 18:38 UTC

This package is auto-updated.

Last update: 2024-08-31 22:18:48 UTC


README

Build Status Latest Stable Version

此扩展简化了在 Twig 中访问枚举值或类常量的方式。

安装它

使用 composer 安装扩展

$ composer require jdecool/twig-constant-accessor-bundle

如果你不使用 Symfony Flex,你需要在 config/bundles.php 配置中启用此扩展

<?php

return [
    // ...
    JDecool\Bundle\TwigConstantAccessorBundle\JDecoolTwigConstantAccessorBundle::class => ['all' => true],
];

在你的配置文件中注册你想访问常量的类

twig_constant_accessor:
    classes:
        - AppBundle\Model\Foo
        - { class: 'AppBundle\Model\Bar' }
        - { class: 'AppBundle\Model\FooBar', alias: 'FooBarAlias' }
        - { class: 'AppBundle\Model\ConstantClass', matches: '/^RULE_/' } # matches accept an regexp compatible with the preg_match function

你也可以使用 twig.constant_accessor 标签在你的容器配置中注册一个类

services:
    my_service:
        class: Namespace\To\ServiceClass
        tags:
            - { name: twig.constant_accessor }

    my_collection:
        class: MyClass
        tags:
            - { name: twig.constant_accessor, alias: 'MyClassAlias' }

    filtered_constants:
        class: ConstantsClass
        tags:
            - { name: twig.constant_accessor, matches: '/^RULE_/' } # matches accept an regexp compatible with the preg_match function

或者,你可以在你的类上使用 #[AsTwigConstantAccessor] 属性

use JDecool\Bundle\TwigConstantAccessorBundle\Annotation\AsTwigConstantAccessor;

#[AsTwigConstantAccessor]
class MyClass
{
    // ...
}

之后,你就可以在你的模板中访问类常量了

{{ ServiceClass.MY_CONSTANT }}
{{ MyClassAlias.KEY }}

{% if 'value' == ServiceClass.My_CONSTANT %}Test is OK{% endif %}