smarty在xampp中成功运行的关键是正确配置php.ini的include_path指向libs目录,并确保templates_c等四个核心目录存在且有写权限;否则将报模板加载失败或编译目录不存在等错误。

Smarty 在 XAMPP 下能跑起来,关键不是“装”,而是路径对得上——尤其是 include_path 和四个核心目录的权限/存在性。 多数报错(比如 Uncaught exception 'SmartyException' with message 'Unable to load template file' 或 the $compile_dir 'templates_c' does not exist)都卡在这两处。
修改 php.ini 的 include_path 必须指向 libs/ 目录,不是 Smarty 根目录
很多人把整个 Smarty 文件夹(含 libs/、demo/、libs/Smarty.class.php)放到 D:/xampp/htdocs/myproject/smarty/,然后在 php.ini 里写:
include_path = ".;D:/xampp/htdocs/myproject/smarty"
这是错的。PHP 找不到 Smarty.class.php,因为 require "Smarty.class.php" 会去 include_path 下直接找这个文件,而不是进子目录。
正确做法是:
- 确认你的 Smarty 解压后,
Smarty.class.php真实路径是D:/xampp/htdocs/myproject/smarty/libs/Smarty.class.php - 在
php.ini中设置:include_path = ".;D:/xampp/htdocs/myproject/smarty/libs"
- 改完必须重启 Apache(仅改配置不重启,等于没改)
- 如果用的是 XAMPP 多版本 PHP(如同时有 PHP 7.4 和 8.2),注意你改的是哪个
php.ini:通常要同步改D:/xampp/php/php.ini和D:/xampp/apache/bin/php.ini
$smarty->template_dir 和 $smarty->compile_dir 必须是绝对路径或 Web 可达的相对路径
Smarty 默认不自动解析相对路径到文档根目录。比如你在 htdocs/myproject/index.php 里写:
XAMPP 8.0.30 是一款免费、开源的跨平台 Web 服务器集成包,专为快速搭建本地 PHP 开发环境而设计。该版本核心组件包括:Apache 2.4.56、MySQL 8.0.33、PHP 8.0.30、phpMyAdmin 5.2.1 等。它支持 Windows、Linux 和 macOS 系统,可让开发者在个人电脑上轻松模拟服务器环境,无需复杂配置即可运行 WordPress、Thin
$smarty->setTemplateDir('./templates/');
它会以 index.php 所在目录为基准,即 D:/xampp/htdocs/myproject/templates/ —— 这没问题;但如果你在子目录(如 myproject/admin/index.php)里也这么写,就会变成找 admin/templates/,出错。
更稳妥的做法是用 __DIR__ 或 $_SERVER['DOCUMENT_ROOT']:
$smarty->setTemplateDir(__DIR__ . '/templates/');
$smarty->setCompileDir($_SERVER['DOCUMENT_ROOT'] . '/myproject/templates_c/');
-
templates_c和cache目录必须存在且 Apache 用户(Windows 下通常是SYSTEM或你当前登录用户)有写权限;否则首次访问直接报does not exist, or is not a directory - 别忽略
templates_c:它不是可选的,Smarty 必须把编译后的 PHP 文件写进去才能运行
常见错误信息对应的真实原因
看到这些报错,不用猜,直接按顺序检查:
-
Fatal error: Uncaught > smarty:无法在第127行的...smarty_internal_templatebase.php中加载模板文件'index.tpl'→ 检查$smarty->template_dir是否真包含index.tpl,用file_exists()打印验证;再确认文件名大小写(Windows 不敏感,Linux 敏感) -
the $compile_dir 'templates_c' does not exist, or is not a directory→ 该目录不存在,或 PHP 进程无权写入(XAMPP 默认 Windows 权限下常因 UAC 或目录只读属性导致) -
Warning: require(Smarty.class.php): failed to open stream→include_path没配对,或require路径写成smarty/Smarty.class.php却没把smarty/放进include_path - 页面空白但无报错 → 开启
$smarty->debugging = true;,或检查 PHP 错误报告是否关闭(error_reporting(E_ALL); ini_set('display_errors', '1');)
最易被忽略的一点:Smarty 3.x 默认使用 SmartyBC.class.php 兼容旧语法,但如果你用的是老教程里的 Smarty.class.php(来自 2.x),而下载的是 3.x 包,就根本找不到这个文件——务必核对下载包版本和 require 的类名是否匹配。










