LiquidRenderer.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Services;
  3. use App\Services\LiquidTags\LiquidTagProduct;
  4. use App\Services\LiquidTags\LiquidTagVideo;
  5. use Liquid\Liquid;
  6. use Liquid\Template;
  7. use Liquid\Cache\File as FileCache;
  8. use App\Services\LiquidTags\LiquidTagPage; // 添加对自定义标签的引用
  9. use App\Services\LiquidFilters\Filters;
  10. use App\Helpers\SiteCache;
  11. class LiquidRenderer
  12. {
  13. protected static ?string $baseTemplatePath = null;
  14. // 渲染 Liquid 模板
  15. public static function render(string $templateName, array $data = []): string
  16. {
  17. self::initializeLiquidSettings();
  18. self::initializeBaseTemplatePath();
  19. $template = self::createTemplateInstance();
  20. $template->registerTag('page', LiquidTagPage::class);
  21. $template->registerTag('product', LiquidTagProduct::class);
  22. $template->registerTag('video', LiquidTagVideo::class);
  23. $template->registerTag('contact', LiquidTagContactUs::class);
  24. $template->registerFilter(Filters::class);
  25. try {
  26. $parsedTemplate = $template->parseFile($templateName);
  27. } catch (\Exception $e) {
  28. throw new \RuntimeException("Template not found: {$templateName}", 0, $e);
  29. }
  30. return $parsedTemplate->render($data);
  31. }
  32. // 初始化基础模板路径
  33. private static function initializeBaseTemplatePath(): void
  34. {
  35. // 获取请求的域名
  36. $domain = getHost();
  37. // 获取分销
  38. $dist=SiteCache::getDist($domain);
  39. // 使用默认值的函数封装,避免重复逻辑
  40. $template_dist_id = $dist['id'] ?? trim(config('liquid.template_dist_id'));
  41. $template_name = $dist['template_name'] ?? trim(config('liquid.template_name'));
  42. if (self::$baseTemplatePath === null) {
  43. self::$baseTemplatePath = rtrim(config('liquid.template_path'), '/') . '/' .
  44. trim($template_dist_id). '/' .
  45. ltrim($template_name, '/');
  46. }
  47. }
  48. // 创建模板实例
  49. private static function createTemplateInstance(): Template
  50. {
  51. $template = new Template(self::$baseTemplatePath);
  52. //$template->setCache(new FileCache(['cache_dir' => storage_path('framework/cache/data')]));
  53. return $template;
  54. }
  55. // 设置 Liquid 渲染的全局配置
  56. private static function initializeLiquidSettings(): void
  57. {
  58. Liquid::set('INCLUDE_SUFFIX', '');
  59. Liquid::set('INCLUDE_PREFIX', '');
  60. Liquid::set('INCLUDE_ALLOW_EXT', true);
  61. Liquid::set('ESCAPE_BY_DEFAULT', true);
  62. }
  63. }