PHP教程:配置smarty开发环境
http://www.itjxue.com 2015-07-17 08:18 来源:未知 点击次数:
首先到 http://www.smarty.net 上下载最新的smarty模板引擎,解压Smarty-2.6.26.zip,改名Smarty-2.6.26目录为smarty。
拷贝smarty目录到你希望的目录 D:\xampp\xampp\smarty。
在php.ini的include_path加入smarty库目录,如下:
include_path = “.;D:\xampp\xampp\php\PEAR;D:\xampp\xampp\smarty\libs”
在你的php项目目录新建两个子目录放配置文件和模板:config 和templates
D:\xampp\xampp\htdocs\config
D:\xampp\xampp\htdocs\templates
smarty项目目录新建两个目录cache和templates_c存放缓存和编译过的模板:
D:\xampp\xampp\smarty\cache
D:\xampp\xampp\smarty\templates_c
在需要调用smarty库的php文件中写入代码:
1 2 3 4 5 6 7 8 9 10 11 |
//this is D:\xampp\xampp\htdocs\index.php //load smarty library require('Smarty.class.php'); $smarty=new Smarty(); $smarty->template_dir='d:/xampp/xampp/htdocs/templates'; //指定模板存放目录 $smarty->config_dir='d:/xampp/xampp/htdocs/config';//指定配置文件目录 $smarty->cache_dir='d:/xampp/xampp/smarty/cache';//指定缓存目录 $smarty->compile_dir='d:/xampp/xampp/smarty/templates_c';//指定编译后的模板目录 $smarty->assign('name','fish boy!'); $smarty->display('index.tpl'); |
再新建一个D:\xampp\xampp\htdocs\templates\index.tpl文件
1 2 3 4 5 6 7 8 9 10 |
<html> <head><title>hello,{$name}!</title> <script language="javascript" type="text/javascript"> alert('{$name}'); </script> </head> <body> hello,{$name}! </body> </html> |
打开http://localhost/index.php 应该会弹出fish boy!警告,然后内容为hello,fish boy!!的页面。
我们可以改进一下,不可能每次需要smarty写这么多配置代码吧。
新建文件 D:\xampp\xampp\htdocs\smarty_connect.php
1 2 3 4 5 6 7 8 9 10 11 |
//load smarty library require('Smarty.class.php'); class smarty_connect extends Smarty { function smarty_connect() {//每次构造自动调用本函数 $this->template_dir='d:/xampp/xampp/htdocs/templates'; $this->config_dir='d:/xampp/xampp/htdocs/config'; $this->cache_dir='d:/xampp/xampp/smarty/cache'; $this->compile_dir='d:/xampp/xampp/smarty/templates_c'; } } |
D:\xampp\xampp\htdocs\index.php改为:
1 2 3 4 |
require('smarty_connect.php'); $smt=new smarty_connect; $smt->assign('name','fish boy!'); $smt->display('index.tpl'); |
index.tpl文件不变,打开localhost/index.php,出现了同样的输出。