首页  >  文章  >  后端开发  >  smarty半小时快速上手入门教程_PHP

smarty半小时快速上手入门教程_PHP

WBOY
WBOY原创
2016-05-31 19:28:54818浏览

本文讲述了smarty快速上手入门的方法,可以让读者在半小时内快速掌握smarty的用法。分享给大家供大家参考。具体实现方法如下:

一、smarty的程序设计部分:

在smarty的模板设计部分我简单的把smarty在模板中的一些常用设置做了简单的介绍,这一节主要来介绍一下如何在smarty中开始我们程序设计。下载Smarty文件放到你们站点中。

index.php代码如下:

代码如下:

/**
*
* @version $Id: index.php
* @package
* @author www.bitsCN.com
* @action 显示实例程序
*/
include_once("./Smarty/Smarty.class.php"); //包含smarty类文件

$smarty = new Smarty(); //建立smarty实例对象$smarty
$smarty->templates("./templates"); //设置模板目录
$smarty->templates_c("./templates_c"); //设置编译目录
$smarty->cache("./cache"); //缓存目录
$smarty->cache_lifetime = 0; //缓存时间
$smarty->caching = true; //缓存方式

$smarty->left_delimiter = "{#";
$smarty->right_delimiter = "#}";
$smarty->assign("name", "zaocha"); //进行模板变量替换
$smarty->display("index.htm"); //编译并显示位于./templates下的index.htm模板
?>


二、解释smarty的程序

我们可以看到,smarty的程序部分实际就是符合php语言规范的一组代码,我们依次来解释一下:

1:/**/语句:

包含的部分为程序篇头注释。主要的内容应该为对程序的作用,版权与作者及编写时间做一个简单的介绍,这在smarty中不是必需的,但从程序的风格来讲,这是一个好的风格。

2:include_once语句:

它将安装到网站的smarty文件包含到当前文件中,注意包含的路径一定要写正确。

3:$smarty = new Smarty():

这一句新建一个Smarty对象$smarty,简单的一个对象的实例化。

4:$smarty->templates(""):

这一句指明$smarty对象使用tpl模板时的路径,它是一个目录,在没有这一句时,Smarty默认的模板路径为当前目录的templates目录,实际在写程序时,我们要将这一句写明,这也是一种好的程序风格。

5:$smarty->templates_c(""):

这一句指明$smarty对象进行编译时的目录。在模板设计篇我们已经知道Smarty是一种编译型模板语言,而这个目录,就是它编译模板的目录,要注意,如果站点位于linux服务器上,请确保

teamplates_c里定义的这个目录具有可写可读权限,默认情况下它的编译目录是当前目录下的templates_c,出于同样的理由我们将其明确的写出来。

6:$smarty->left_delimiter与$smarty->right_delimiter:

指明在查找模板变量时的左右分割符。默认情况下为"{"与"}",但在实际中因为我们要在模板中使用