1.首先到Smarty官方网站下载最新套件: http://www.smarty.net/
2.程序的资料夹设定.
程序的主资料夹是「C:\Program Files\xampp\htdocs\demo」。

在 Linux 底下,请记得将 templates_c 的权限变更为 777 。Windows 下则将其只读取消。
3.我们先设定 Smarty 的路径,请将以下这个档案命名为 main.php ,并
放置到主资料夹下:
<?php
include "class/Smarty.class.php";
define('__SITE_ROOT', '../demo');
$tpl = new Smarty();
$tpl->template_dir = __SITE_ROOT . "/templates/";
$tpl->compile_dir = __SITE_ROOT . "/templates_c/";
$tpl->config_dir = __SITE_ROOT . "/configs/";
$tpl->cache_dir = __SITE_ROOT . "/cache/";
$tpl->left_delimiter = '<{';
$tpl->right_delimiter = '}>';
?>
include "class/Smarty.class.php";
define('__SITE_ROOT', '../demo');
$tpl = new Smarty();
$tpl->template_dir = __SITE_ROOT . "/templates/";
$tpl->compile_dir = __SITE_ROOT . "/templates_c/";
$tpl->config_dir = __SITE_ROOT . "/configs/";
$tpl->cache_dir = __SITE_ROOT . "/cache/";
$tpl->left_delimiter = '<{';
$tpl->right_delimiter = '}>';
?>
Smarty 的模版路径设定好后,程序会依照这个路径来抓所有模版的相对位置 (范例中是 '../demo/templates/' ) 。然后我们用 display() 这个 Smarty 方法来显示我们的模版。
接下来我们在 templates 资料夹下放置一个 test.htm.
templates/test.htm:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title><{$title}></title>
</head>
<body>
<{$content}>
</body>
</html>
现在我们要将上面的模版显示出来,并将网页标题 ($title) 与内容 ($content) 更换,请将以下档案内容命名为 test.php ,并放置在主资料夹下:
test.php:
<?php
require "main.php";
$tpl->assign("title", "测试用的网页标题");
$tpl->assign("content", "测试用的网页内容");
// 上面两行也可以用这行代替
// $tpl->assign(array("title" => "测试用的网页标题", "content" => "测试用的网页内容"));
$tpl->display('test.htm');
?>
templates/test.htm:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title><{$title}></title>
</head>
<body>
<{$content}>
</body>
</html>
现在我们要将上面的模版显示出来,并将网页标题 ($title) 与内容 ($content) 更换,请将以下档案内容命名为 test.php ,并放置在主资料夹下:
test.php:
<?php
require "main.php";
$tpl->assign("title", "测试用的网页标题");
$tpl->assign("content", "测试用的网页内容");
// 上面两行也可以用这行代替
// $tpl->assign(array("title" => "测试用的网页标题", "content" => "测试用的网页内容"));
$tpl->display('test.htm');
?>
请打开浏览器,输入 http://localhost/test.php 试试看.
最后我们整理一下整个 Smarty 程序撰写步骤:
Step 1. 加载 Smarty 模版引擎。
Step 2. 建立 Smarty 对象。
Step 3. 设定 Smarty 对象的参数。
Step 4. 在程序中处理变量后,再用 Smarty 的 assign 方法将变量置入模版里。
Step 5. 利用 Smarty 的 display 方法将网页秀出。
Step 1. 加载 Smarty 模版引擎。
Step 2. 建立 Smarty 对象。
Step 3. 设定 Smarty 对象的参数。
Step 4. 在程序中处理变量后,再用 Smarty 的 assign 方法将变量置入模版里。
Step 5. 利用 Smarty 的 display 方法将网页秀出。



