| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <?php
- declare(strict_types=1);
- namespace Glacier\Core;
- use Twig\Environment;
- use Twig\Loader\FilesystemLoader;
- /**
- * Twig 渲染封装。
- * - 模板目录:app/views(模块模板后续追加 app/modules/<name>/views)
- * - 默认自动转义(安全基线:XSS)
- * - 开发环境关闭编译缓存,生产开启(storage/cache/twig)
- * - 全局变量:app_name / base_url(模板生成链接,杜绝物理路径)
- */
- final class View
- {
- private static ?Environment $twig = null;
- public static function render(string $template, array $data = []): string
- {
- return self::twig()->render($template, $data);
- }
- /**
- * 追加模板目录(模块视图:app/modules/<name>/views)。
- * 带命名空间注册后以 @<namespace>/<template> 引用,避免多模块同名模板冲突。
- */
- public static function addPath(string $path, ?string $namespace = null): void
- {
- $loader = self::twig()->getLoader();
- if ($loader instanceof FilesystemLoader) {
- $loader->addPath(rtrim($path, '/\\'), $namespace);
- }
- }
- public static function twig(): Environment
- {
- if (self::$twig === null) {
- $cacheDir = Config::get('storage.cache', APP_ROOT . '/storage/cache') . '/twig';
- $debug = (bool) Config::get('app.debug', false);
- $loader = new FilesystemLoader([
- APP_ROOT . '/app/views',
- ]);
- self::$twig = new Environment($loader, [
- 'cache' => $debug ? false : $cacheDir,
- 'autoescape' => 'html',
- 'charset' => 'UTF-8',
- 'strict_variables' => false,
- 'debug' => $debug,
- ]);
- self::$twig->addGlobal('app_name', Config::get('app.name', 'Glacier'));
- self::$twig->addGlobal('base_url', (string) Config::get('app.base_url', ''));
- self::$twig->addGlobal('csrf_token', Session::csrfToken());
- }
- return self::$twig;
- }
- }
|