您的位置:首页 > 其它

Smarty快速入门之二

2011-06-08 13:57 169 查看
为了以后更方便的使用smarty,我们可以将“加载Smarty 模版引擎”、“建立 Smarty 对象”、“设定Smarty 对象的参数”这三步放到一个公共的php文件内,以后在需要使用的地方我们直接reuqire一下,即可,例如:

1. 建立一个main.php
<?php
include 'smarty/Smarty.class.php';
//下次程序移植时只需要修改ROOT指向位置即可~
const DIR_SEP = DIRECTORY_SEPARATOR;
define('ROOT', 'D:'.DIR_SEP.'_PHP_Test'.DIR_SEP.'Test2'.DIR_SEP); $tpl = new Smarty();
$tpl->template_dir	= ROOT.'templates'.DIR_SEP;
$tpl->complie_dir	= ROOT.'templates_c'.DIR_SEP;
$tpl->config_dir	= ROOT.'configs'.DIR_SEP;
$tpl->cache_dir		= ROOT.'cache'.DIR_SEP;
$tpl->left_delimiter = '<{';
$tpl->right_delimiter = '}>';
?>

注1:此处为何要使用DIRECTORY_SEPARATOR?(点击查看)
注2:left_delimiter和right_delimiter为左右结束符变量,此处可定义为其他字符串(默认为{})。

2. 在templates下,新建立一个test.htm
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><{$title}></title>
</head>
<body>
	<{$content}>
</body>
</html>


3. 调用模板页给title和content填充内容,新建一个test_smarty_1.php
<?php 
require 'main.php';
$tpl->assign('title', 'New Message');
$tpl->assign('content', 'This is test smarty!');
$tpl->display('test.htm');
?>

也可以这样写
<?php 
require 'main.php';
$tpl->assign(array('title'=>'NewMessage', 'content'=>'This is test smarty!'));
$tpl->display('test.htm');
?>


输出结果:
页面title显示:NewMessage
页面内容显示:'This is test smarty!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: