LiquidRenderer.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace App\Services;
  3. use Liquid\Template;
  4. use Liquid\Cache\File as FileCache;
  5. use Illuminate\Support\Facades\File;
  6. class LiquidRenderer
  7. {
  8. protected static $baseTemplatePath;
  9. public static function render(string $templateName, array $data = []): string
  10. {
  11. // 初始化基础模板路径(仅在首次调用时)
  12. if (!self::$baseTemplatePath) {
  13. self::$baseTemplatePath = config('liquid.template_path');
  14. }
  15. // 查找模板文件
  16. $templatePath = self::findTemplate($templateName);
  17. if (!$templatePath) {
  18. throw new \Exception("Template not found: {$templateName}");
  19. }
  20. // 读取 Liquid 模板文件内容
  21. $templateContent = File::get($templatePath);
  22. // 创建并解析模板
  23. $template = new Template();
  24. $template->setCache(new FileCache(['cache_dir' => storage_path('framework/cache/data')]));
  25. $template->parse($templateContent);
  26. // 渲染模板并返回结果
  27. return $template->render($data);
  28. }
  29. protected static function findTemplate(string $templateName): ?string
  30. {
  31. // 如果模板名没有以 .liquid 结尾,则添加 .liquid 扩展名
  32. if (pathinfo($templateName, PATHINFO_EXTENSION) !== 'liquid') {
  33. $templateName .= '.liquid';
  34. }
  35. // 处理模板名中的 . 号,将其转换为目录分隔符(不包括扩展名)
  36. $templateNameWithoutExtension = pathinfo($templateName, PATHINFO_FILENAME);
  37. $templatePathSegments = explode('.', $templateNameWithoutExtension);
  38. $relativePath = implode(DIRECTORY_SEPARATOR, $templatePathSegments) . '.liquid';
  39. // 构建预期的模板路径
  40. $expectedPath = self::$baseTemplatePath . DIRECTORY_SEPARATOR . $relativePath;
  41. if (File::exists($expectedPath)) {
  42. return $expectedPath;
  43. }
  44. return null;
  45. }
  46. }