constant-exposure/constant-exposure-bundle

将 PHP 常量暴露给前端。

v2.4.0 2023-11-01 11:23 UTC

README

Version License

如果需要将常量暴露给前端,这个 Symfony 扩展包 非常有用。

安装

Composer

composer require constant-exposure/constant-exposure-bundle:^2.2

加载扩展包

config/bundles.php 文件中添加以下行

return [
    ...
    ConstantExposureBundle\ConstantExposureBundle::class => ['all' => true],
];

使用方法

定义要暴露的常量

在你的项目中创建一个 config/packages/constant_exposure.yaml 文件。然后,配置要暴露的常量。

constant_exposure:
    parameter:
        debug: '%kernel.debug%'
        sentry_dsn: '%env(SENTRY_DSN)%'
        password_expire: !php/const App\Entity\Password::EXPIRE_PASSWORD 

在 JavaScript 中使用常量

在你的 Twig 模板中添加此行。将作为参数传递的名称传递给 JavaScript 对象。

{{ constant_exposure_object('ConstantExposure') }}

在 JavaScript 中获取它们

ConstantExposure.getParameter(PARAMETER_NAME [, DEFAUlT_VALUE = null] );
// Check if you are in debug mode
const isDebug = ConstantExposure.getParameter('debug');

// If sentry_dsn is not defined, default value is an empty string
const sentryDsn = ConstantExopsure.getParameter('sentry_dsn', '');

路由暴露

如果你需要在路由上暴露常量,在你的路由文件中添加以下行

constant_exposure:
    resource: "@ConstantExposureBundle/Resources/config/routing.yaml"

然后,你可以通过以下 URL 访问它

  • /constant-exposure.json 用于 JSON 格式
  • /constant-exposure.xml 用于 XML 格式
  • /constant-exposure.csv 用于 CSV 格式