Smarty模板引擎应用

来源:互联网 发布:编程小白 编辑:程序博客网 时间:2024/05/16 05:01

1.基本安装:
require('Smarty.class.php');
$smarty = new Smarty;

require('/usr/local/lib/php/Smarty/Smarty.class.php');
$smarty = new Smarty;
 


2. Smarty要求4个目录,默认下命名为:tempalates, templates_c, configs and cache。每个都是可以自定义的,可以修改Smarty类属性: $template_dir, $compile_dir, $config_dir, and $cache_dir respectively。强烈推荐你为每个用到smarty的应用程序设置单一的目录!

3.
require('Smarty.class.php');

$smarty = new Smarty;

$smarty->template_dir = '/web/www.mydomain.com/smarty/guestbook/templates/';
$smarty->compile_dir = '/web/www.mydomain.com/smarty/guestbook/templates_c/';
$smarty->config_dir = '/web/www.mydomain.com/smarty/guestbook/configs/';
$smarty->cache_dir = '/web/www.mydomain.com/smarty/guestbook/cache/';

$smarty->assign('name','Ned');

$smarty->display('index.tpl');
 


3.扩展,一个更灵活一点的配置Smarty的方法是扩展类,和初始化你的smarty环境。
// load Smarty library
require('Smarty.class.php');

class Smarty_GuestBook extends Smarty {

 function Smarty_GuestBook() {
 
         // Class Constructor. These automatically get set with each new instance.
 //类构造函数.创建实例的时候自动配置

        $this->Smarty();

        $this->template_dir = '/web/www.mydomain.com/smarty/guestbook/templates/';
        $this->compile_dir = '/web/www.mydomain.com/smarty/guestbook/templates_c/';
        $this->config_dir = '/web/www.mydomain.com/smarty/guestbook/configs/';
        $this->cache_dir = '/web/www.mydomain.com/smarty/guestbook/cache/';
       
        $this->caching = true;
        $this->assign('app_name','Guest Book');
 }

}

 

4.基本语法:
{} 定界符,
{* this is a comment *} 注释,

变量
$smarty = new Smarty;$smarty->assign('firstname', 'Doug');
$smarty->assign('lastLoginDate', 'January 11th, 2001');
$smarty->display('index.tpl');

Hello {$firstname},


数组变量
$smarty = new Smarty;
$smarty->assign('Contacts',
 array('fax' => '555-222-9876',
 'email' => 'zaphod@slartibartfast.com',
 'phone' => array('home' => '555-444-3333',
 'cell' => '555-111-1234')));
$smarty->display('index.tpl');


{$Contacts[0]}<br>
{$Contacts[1]}<br>
{$Contacts.fax}<br>
{$Contacts.email}<br>

从配置文件读取变量:
配置文件中的变量需要通过用两个"#"或者是smarty的保留变量 $smarty.config.来调用

 

 

 

 

 

 

 

原创粉丝点击