1. 加载Smarty类库,即加载Smarty.class.php文件,这里使用的是绝对地址。为了在配置其他路径时不用输入过长的地址字符串,之前还声明了两个常量:服务器地址常量和Smarty路径常量。两个常量连接起来就是Smarty类库所在的目录。
//index.php
<?php
/*
* Created on 2011-7-8
*
* @author : 低调走过
* @ Q Q : 361789273
* @E-mail : 361789273@qq.com
*/
?>
<?php
define('BASE_PATH', $_SERVER['DOCUMENT_ROOT']);
define('SMARTY_PATH', '/Smarty/');
require BASE_PATH.SMARTY_PATH.'Smarty.class.php';
$smarty = new Smarty;
$smarty->template_dir = BASE_PATH.SMARTY_PATH.'templates/';
$smarty->compile_dir = BASE_PATH.SMARTY_PATH.'templates_c/';
$smarty->config_dir = BASE_PATH.SMARTY_PATH.'configs/';
$smarty->cache_dir = BASE_PATH.SMARTY_PATH.'cache/';
$smarty->left_delimiter = '{%';
$smarty->right_delimiter = '%}';
$smarty->assign('title', '第一个Smarty程序');
$smarty->assign('content', 'Hello, Welcome to study \'Smarty\'!');
$smarty->display('index.tpl');
?>
<!--index.tpl-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title> {%$title%} </title>
</head>
<body>
{%$content%}
</body>
</html>
2. 保存新建的4个目录的绝对路径到各自的变量中。在第二步时创建4个目录,分别是templates、templates_c、configs和cache。这4个目录各有用途,如果没有配置目录的地址,那么服务器默认的路径就是当前执行文件所在的路径。
3. 给模板赋值。设置成功后,给指定的模板复制。赋值应用的是assign()方法。
4. 显示模板。赋值完成后,调用display()方法来显示页面。实际上用户看到的页面是templates模板目录下的index.tpl模板文件,而作为首页的index.php只是用来传递结果和显示模板。