知识点 词汇表 联系我们
按类别浏览
内容搜索    
当前位置:WEB开发技术知识库(www.cn-web.com) .: PHP技术 .: 基础教程 .: Smarty的基本安装使用教程

Smarty的基本安装使用教程


Smarty使用一个叫做'SMARTY_DIR'的php常量作为它的系统库目录。如果你的应用程序可以找到 Smarty.class.php文件,那么你就不需要设置SMARTY_DIR,Smarty将会自己运作。
但是,如果 Smarty.class.php不在你的include_path(php.ini里的一项设置)里,或者你没有在应用程序里设置它的绝对路径的时候,你就必须手动配置SMARTY_DIR 了(大多数程序都如此)SMARTY_DIR必须包含结尾斜杠。
 
以下进行举例说明如何在你的系统中配置smarty引擎:
 
在一php页面中加入对samrty的引用:
require('Smarty.class.php');
$smarty ? new Smarty;
运行以后,会发现有"未找到Smarty.class.php 文件"的错误。这是因为系统没有正确引用Smarty.class.php的路径。我们将它改为绝对路径看下:
require('/Smarty/Smarty.class.php');
$smarty = new Smarty;
OK,这样我们就可以引用到库文件Smarty.class.php了。
Smarty要求4个目录,默认下命名为:tempalates, templates_c, configs ,cache
每个都是可以自定义的,可以修改Smarty类属性: $template_dir, $compile_dir, $config_dir,$cache_dir 。
官方推荐为每个用到smarty的应用程序设置单一的目录!
为了安全,推荐将这四个目录与网页程序分开目录来存储,以名通过浏览器地址能访问到。

我在这里的安装目录是d:/web/www.cn_web.com/smarty/目录下。然后运行的网页放入d:/web/www.cn_web.com/test/目录下,这里为index.php文件。
 
OK,看下我们刚刚设置的文件结构目录:
d:/web/www.cn_web.com/smarty/Smarty.class.php
d:/web/www.cn_web.com/smarty/Smarty_Compiler.class.php
d:/web/www.cn_web.com/smarty/Config_File.class.php
d:/web/www.cn_web.com/smarty/debug.tpl
d:/web/www.cn_web.com/smarty/core/*.php
d:/web/www.cn_web.com/smarty/plugins/*.php

d:/web/www.cn_web.com/smarty/test/templates/
d:/web/www.cn_web.com/smarty/test/templates_c/(需要权限为可写)
d:/web/www.cn_web.com/smarty/test/configs/
d:/web/www.cn_web.com/smarty/test/cache/(需要权限为可写)

d:/web/www.cn_web.com/smarty/test/index.php
 注意:$compile_dir 和$cache_dir两个目录的权限必须为可写
 
实例中我们创建index.tpl文件让smarty载入.这个文件放在 $template_dir目录里。
代码:
{* Smarty *}
Hello, {$name}!
{* Smarty *} 是在模板里的注释标识。
 
OK,看完这些,我们看下index.php代码如何写,如果与模板文件index.tpl来融合:
// load Smarty library
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->template_dir = '/smarty/test/templates/';
$smarty->compile_dir = '/smarty/test/templates_c/';
$smarty->config_dir = '/smarty/test/configs/';
$smarty->cache_dir = '/smarty/test/cache/';
$smarty->assign('name','laohan');
$smarty->display('index.tpl');
好,运行index.php看下,已经成功将代码页与模板页整合了。
 
如果我们要做系统,页面肯定不只一个,那么每个页面都到上面这样引用路径肯定不好,下面我们就来看下如何扩展smart以更灵活的初始化我们的smarty环境。
 
我们在/smarty/inc/目录下建立文件global.php。
代码:
// load Smarty library
require('Smarty.class.php');

class Smarty_test extends Smarty {
 function Smarty_test () {
 //类构造函数.创建实例的时候自动配置
  $this->Smarty();
  $this->template_dir = '/smarty/test/templates/';
$this->compile_dir = '/smarty/test/templates_c/';
$this->config_dir = '/smarty/test/configs/';
$this->cache_dir = '/smarty/test/cache/';

  
  $this->caching = true;
  $this->assign('app_name',test_cn_web');
 }
}

最后我们完善一下刚才的index.php文件 吧:
代码:
require('inc/global.php');
$smarty = new Smarty_test ;
$smarty->assign('name','Ned');
$smarty->display('index.tpl');
 
老韩于07.12.17


对此文章打分评级

用户评论

增加评论
此文章还没有任何评论!
网站地图 - 知识词汇 - 全文检索 - 广告服务 - 帮助中心 - 联系我们
.:www.cn-web.com
网站技术开发联盟之WEB开发技术知识库
联系人:老韩(QQ:5679551)
晋ICP备07003487号