hostnet/entity-translation-bundle

用于渲染枚举类优雅名称的翻译包。

1.0.9 2024-06-06 07:59 UTC

This package is auto-updated.

Last update: 2024-09-06 08:54:00 UTC


README

此包允许自动化将枚举值翻译为人类可读的字符串,例如,显示状态文本而不是状态代码的枚举值。

本质上,它允许将值映射到类名域内的翻译。实际上这意味着您可以使用它如下

$status_text = $translator->trans(SetupStatus::DONE, [], SetupStatus::class);

或者在twig模板中

{{ constant('AppBundle\\Entity\\SetupStatus::DONE') | trans([], 'AppBundle\\Entity\\SetupStatus') }}

要求

实体翻译包需要至少php 7.3和symfony翻译组件。对于具体要求,请检查composer.json

安装

安装相当简单,此包在packagist上可用。

示例

$ composer require hostnet/entity-translation-bundle

在AppKernel中注册该包

此包使用框架包注册的翻译器。因此,请确保在FrameworkBundle之后注册此包。

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            // ...
            new AppBundle\AppBundle(),
            new Hostnet\Bundle\EntityTranslationBundle\HostnetEntityTranslationBundle(),
            // ...
        ];

        return $bundles;
    }
}

用法

只需将enum.en.yml添加到您某个包的Resources文件夹中的翻译文件夹。这将包含特定枚举的翻译。翻译键是全限定命名空间的小写,并且CamelCase单词之间用_分隔。例如,枚举AppBundle\Entity\SetupStatus将变为app_bundle.entity.setup_status

考虑以下类

<?php
namespace AppBundle\Entity;

final class SetupStatus
{
    const PENDING           = 1;
    const DONE              = 2;
    const ERROR             = 3;
    const REVERTING_CHANGES = 4;
}

您的AppBundle/Resources/translations/enum.en.yml可能看起来如下

app_bundle:
    entity:
        setup_status:
            pending           : Installation Pending.
            done              : Installation Complete.
            error             : An error occured.
            reverting_changes : Reverting changes.

翻译器将随后获取您的翻译文件中定义的所有枚举类。