Smarty 小试牛刀
要在Smarty模板引擎中创建一个简单的 "Hello World" 示例,你需要遵循以下步骤
1、创建模板文件 在你的模板目录(假设为templates/)中创建一个名为hello.tpl的文件。这个文件将包含基本的HTML结构和Smarty的模板语法。
2、编写模板内容 在hello.tpl文件中,写入以下内容:
<!DOCTYPE html> <html> <head> <title>Hello World with Smarty</title> </head> <body> <h1>Hello, {$name}!</h1> </body> </html>
这里,{$name} 是一个变量占位符,稍后将在PHP脚本中赋值。
3、配置Smarty
在你的PHP脚本中,配置Smarty实例并指定模板目录、编译目录和缓存目录。
require_once './lib/Smarty.class.php'; // 确保路径正确 $smarty = new Smarty(); $smarty->template_dir = './templates'; $smarty->compile_dir = './templates/compile'; $smarty->cache_dir = './templates/cache';
4、分配变量
在PHP脚本中,使用assign方法为模板中的变量赋值。
$smarty->assign('name', 'World');
5、渲染模板
使用display方法来渲染模板,并显示结果。
$smarty->display('hello.tpl');
6、运行PHP脚本
当你运行这个PHP脚本时,Smarty将使用hello.tpl模板文件来生成HTML内容,其中{$name}将被替换为World。最终输出将是:
<!DOCTYPE html> <html> <head> <title>Hello World with Smarty</title> </head> <body> <h1>Hello, World!</h1> </body> </html>
确保你的PHP环境配置正确,并且Smarty类文件的路径正确无误。如果你使用的是Smarty 3或更高版本,还需要确保Smarty的缓存目录和编译目录具有写权限。如果你遇到任何问题,检查文件路径、权限设置以及Smarty的配置是否正确。