SmartyEngine.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\View\Engine;
  4. use Hyperf\Contract\ConfigInterface;
  5. use Hyperf\View\Engine\EngineInterface;
  6. use Smarty;
  7. class SmartyEngine implements EngineInterface
  8. {
  9. protected Smarty $smarty;
  10. public function __construct(protected ConfigInterface $config)
  11. {
  12. $this->smarty = new Smarty();
  13. // 确保路径以斜杠结尾
  14. $viewPath = rtrim($this->config->get('view.config.view_path'), '/') . '/';
  15. $compileDir = rtrim($this->config->get('view.config.compile_dir'), '/') . '/';
  16. $this->smarty->setTemplateDir($viewPath);
  17. $this->smarty->setCompileDir($compileDir);
  18. $this->smarty->setLeftDelimiter($options['left_delimiter'] ?? '{{');
  19. $this->smarty->setRightDelimiter($options['right_delimiter'] ?? '}}');
  20. // 调试输出路径(生产环境移除)
  21. error_log("Smarty模板路径: " . $viewPath);
  22. }
  23. public function render(string $template, array $data, array $config): string
  24. {
  25. foreach ($data as $key => $value) {
  26. $this->smarty->assign($key, $value);
  27. }
  28. return $this->smarty->fetch($template);
  29. }
  30. }