SmartyEngine.php 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  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. // 调试输出路径(生产环境移除)
  19. error_log("Smarty模板路径: " . $viewPath);
  20. }
  21. public function render(string $template, array $data, array $config): string
  22. {
  23. foreach ($data as $key => $value) {
  24. $this->smarty->assign($key, $value);
  25. }
  26. return $this->smarty->fetch($template);
  27. }
  28. }