View.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. declare(strict_types=1);
  3. namespace Glacier\Core;
  4. use Twig\Environment;
  5. use Twig\Loader\FilesystemLoader;
  6. /**
  7. * Twig 渲染封装。
  8. * - 模板目录:app/views(模块模板后续追加 app/modules/<name>/views)
  9. * - 默认自动转义(安全基线:XSS)
  10. * - 开发环境关闭编译缓存,生产开启(storage/cache/twig)
  11. * - 全局变量:app_name / base_url(模板生成链接,杜绝物理路径)
  12. */
  13. final class View
  14. {
  15. private static ?Environment $twig = null;
  16. public static function render(string $template, array $data = []): string
  17. {
  18. return self::twig()->render($template, $data);
  19. }
  20. /**
  21. * 追加模板目录(模块视图:app/modules/<name>/views)。
  22. * 带命名空间注册后以 @<namespace>/<template> 引用,避免多模块同名模板冲突。
  23. */
  24. public static function addPath(string $path, ?string $namespace = null): void
  25. {
  26. $loader = self::twig()->getLoader();
  27. if ($loader instanceof FilesystemLoader) {
  28. $loader->addPath(rtrim($path, '/\\'), $namespace);
  29. }
  30. }
  31. public static function twig(): Environment
  32. {
  33. if (self::$twig === null) {
  34. $cacheDir = Config::get('storage.cache', APP_ROOT . '/storage/cache') . '/twig';
  35. $debug = (bool) Config::get('app.debug', false);
  36. $loader = new FilesystemLoader([
  37. APP_ROOT . '/app/views',
  38. ]);
  39. self::$twig = new Environment($loader, [
  40. 'cache' => $debug ? false : $cacheDir,
  41. 'autoescape' => 'html',
  42. 'charset' => 'UTF-8',
  43. 'strict_variables' => false,
  44. 'debug' => $debug,
  45. ]);
  46. self::$twig->addGlobal('app_name', Config::get('app.name', 'Glacier'));
  47. self::$twig->addGlobal('base_url', (string) Config::get('app.base_url', ''));
  48. }
  49. return self::$twig;
  50. }
  51. }