1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <?php
- namespace App\Services;
- use App\Services\LiquidTags\LiquidTagProduct;
- use App\Services\LiquidTags\LiquidTagVideo;
- use Liquid\Liquid;
- use Liquid\Template;
- use Liquid\Cache\File as FileCache;
- use App\Services\LiquidTags\LiquidTagPage; // 添加对自定义标签的引用
- use App\Services\LiquidFilters\Filters;
- use App\Helpers\SiteCache;
- class LiquidRenderer
- {
- protected static ?string $baseTemplatePath = null;
- // 渲染 Liquid 模板
- public static function render(string $templateName, array $data = []): string
- {
- self::initializeLiquidSettings();
- self::initializeBaseTemplatePath();
- $template = self::createTemplateInstance();
- $template->registerTag('page', LiquidTagPage::class);
- $template->registerTag('product', LiquidTagProduct::class);
- $template->registerTag('video', LiquidTagVideo::class);
- $template->registerTag('contact', LiquidTagContactUs::class);
- $template->registerFilter(Filters::class);
- try {
- $parsedTemplate = $template->parseFile($templateName);
- } catch (\Exception $e) {
- throw new \RuntimeException("Template not found: {$templateName}", 0, $e);
- }
- return $parsedTemplate->render($data);
- }
- // 初始化基础模板路径
- private static function initializeBaseTemplatePath(): void
- {
- // 获取请求的域名
- $domain = getHost();
- // 获取分销
- $dist=SiteCache::getDist($domain);
- // 使用默认值的函数封装,避免重复逻辑
- $template_dist_id = $dist['id'] ?? trim(config('liquid.template_dist_id'));
- $template_name = $dist['template_name'] ?? trim(config('liquid.template_name'));
- if (self::$baseTemplatePath === null) {
- self::$baseTemplatePath = rtrim(config('liquid.template_path'), '/') . '/' .
- trim($template_dist_id). '/' .
- ltrim($template_name, '/');
- }
- }
- // 创建模板实例
- private static function createTemplateInstance(): Template
- {
- $template = new Template(self::$baseTemplatePath);
- //$template->setCache(new FileCache(['cache_dir' => storage_path('framework/cache/data')]));
- return $template;
- }
- // 设置 Liquid 渲染的全局配置
- private static function initializeLiquidSettings(): void
- {
- Liquid::set('INCLUDE_SUFFIX', '');
- Liquid::set('INCLUDE_PREFIX', '');
- Liquid::set('INCLUDE_ALLOW_EXT', true);
- Liquid::set('ESCAPE_BY_DEFAULT', true);
- }
- }
|