View.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. public static function twig(): Environment
  21. {
  22. if (self::$twig === null) {
  23. $cacheDir = Config::get('storage.cache', APP_ROOT . '/storage/cache') . '/twig';
  24. $debug = (bool) Config::get('app.debug', false);
  25. $loader = new FilesystemLoader([
  26. APP_ROOT . '/app/views',
  27. ]);
  28. self::$twig = new Environment($loader, [
  29. 'cache' => $debug ? false : $cacheDir,
  30. 'autoescape' => 'html',
  31. 'charset' => 'UTF-8',
  32. 'strict_variables' => false,
  33. 'debug' => $debug,
  34. ]);
  35. self::$twig->addGlobal('app_name', Config::get('app.name', 'Glacier'));
  36. self::$twig->addGlobal('base_url', (string) Config::get('app.base_url', ''));
  37. }
  38. return self::$twig;
  39. }
  40. }