php专区

 首页 > php专区 > PHP应用 > 常用功能 > smarty模板的使用方法实例分析

smarty模板的使用方法实例分析

分享到:
【字体:
导读:
         [导读] smarty模板的使用方法实例分析...

本文实例讲述了smarty模板的使用方法。分享给大家供大家参考,具体如下:

这里以smarty3为例

首先, 在官网下载smarty3模板文件,然后解压。

在解压之后的文件夹中,libs是smarty模板的核心文件,demo里面有示例程序。

我们把libs文件夹复制到我们的工作目录,然后重命名为smarty。

image.png

假设我们在controller目录下的index.php中使用smarty模板。

index.php

debugging = false;  //开启debug模式
$smarty->caching = true;  //开启缓存
$smarty->cache_lifetime = 120; //缓存时间
$smarty->left_delimiter = 'right_delimiter = '}>';  //右定界符
$smarty->template_dir = detest_dir.'/../view/';  //视图目录
$smarty->compile_dir = detest_dir . '/../smarty/compile/';  //编译目录
$smarty->config_dir = detest_dir . '/../smarty/configs/'; //配置目录
$smarty->cache_dir = detest_dir . '/../smarty/cache/';  //缓存目录
$list = range('A', 'D');
$smarty->assign("list", $list);
$smarty->assign("name", "zhezhao");
$smarty->display('index.html');

模板文件index.html

$v }> :

上述方法的优点是使用起来配置比较简单,缺点也是显而易见的,我们controller目录下可能有很多页面调用smarty模板,在每个页面都需要将上述方法配置一遍。

解决方法有两种:

将smarty模板的配置信息写到一个文件中,然后其他页面可以通过包含该文件使用smarty对象。

require '../smarty/Smarty.class.php';
$smarty = new Smarty;
$smarty->debugging = false;  //开启debug模式
$smarty->caching = true;  //开启缓存
$smarty->cache_lifetime = 120; //缓存时间
$smarty->left_delimiter = 'right_delimiter = '}>';  //右定界符
$smarty->template_dir = detest_dir.'/../view/';  //视图目录
$smarty->compile_dir = detest_dir . '/../smarty/compile/';  //编译目录
$smarty->config_dir = detest_dir . '/../smarty/configs/'; //配置目录
$smarty->cache_dir = detest_dir . '/../smarty/cache/';  //缓存目录

我们自己编写一个类,继承自Smarty类,然后将配置信息写在构造函数中。

我们编写mySmarty类

debugging = false; //开启debug模式
    $this->caching = true; //开启缓存
    $this->cache_lifetime = 120;  //缓存时间
    $this->left_delimiter = 'right_delimiter = '}>'; //右定界符
    $this->setTemplateDir(detest_dir.'/../view/');  //视图目录
    $this->setCompileDir(detest_dir . '/../smarty/compile/'); //编译目录
    $this->setConfigDir(detest_dir . '/../smarty/configs/'); //配置目录
    $this->setCacheDir(detest_dir . '/../smarty/cache/'); //缓存目录
  }
}

此时,controller里面的index.php代码可优化为:

assign("list", $list);
$smarty->assign("name", "zhezhao");
$smarty->display('index.html');

最后送上福利:smarty3 chm官方文档

希望本文所述对大家基于smarty模板的PHP程序设计有所帮助。

分享到:
php文件包含的几种方式总结
四种语句 PHP中有四个加载文件的语句:include、require、include_once、require_once。 基本语法 require:require函数一般放在PHP脚本的最前面,PHP执行前就会先读入require指定引入的文件,包含并尝试执行引入的脚本文件。require的工作方式是提高PHP的执行效率,当它在同一个网页中解释过一次后,第二次便不会解释。但...
PHP MVC框架中类的自动加载机制实例分析
本文实例讲述了PHP MVC框架中类的自动加载机制。分享给大家供大家参考,具体如下: 原文 实现类的自动加载主要使用到了set_include_path和spl_autoload_register函数。 set_include_path用于提前设置好可能会加载的类的路径。 spl_autoload_register用于调用相关自动加载所需类的函数,实现自动载入的功能。 有一点要注意...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……