constant-exposure / constant-exposure-bundle
将 PHP 常量暴露给前端。
v2.4.0
2023-11-01 11:23 UTC
Requires
- php: >=7.2
- symfony/cache: ^3.4|^4.0|^5.0|^6.0
- symfony/config: ^3.4|^4.0|^5.0|^6.0
- symfony/dependency-injection: ^3.4|^4.0|^5.0|^6.0
- symfony/framework-bundle: ^3.4|^4.0|^5.0|^6.0
- symfony/http-foundation: ^3.4|^4.0|^5.0|^6.0
- symfony/http-kernel: ^3.4|^4.0|^5.0|^6.0
- symfony/serializer: ^3.4|^4.0|^5.0|^6.0
- symfony/twig-bundle: ^3.4|^4.0|^5.0|^6.0
Requires (Dev)
- phake/phake: @stable
- phpstan/phpstan-symfony: ^0.12
- symfony/phpunit-bridge: ^4.4
This package is not auto-updated.
Last update: 2024-09-18 15:42:36 UTC
README
如果需要将常量暴露给前端,这个 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 格式