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

本文提供了一个Smarty3模板的使用实例,详细介绍了如何配置和优化Smarty,包括设置debug模式、缓存、模板目录等。通过创建自定义类mySmarty简化配置过程,以提高代码复用性。
摘要由CSDN通过智能技术生成

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

这里以smarty3为例

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

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

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

a4d84bc816f96fcbe280dc746606f881.png

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

index.php

require '../smarty/Smarty.class.php';

$smarty = new Smarty;

$smarty->debugging = false; //开启debug模式

$smarty->caching = true; //开启缓存

$smarty->cache_lifetime = 120; //缓存时间

$smarty->left_delimiter = '

$smarty->right_delimiter = '}>'; //右定界符

$smarty->template_dir = __DIR__.'/../view/'; //视图目录

$smarty->compile_dir = __DIR__ . '/../smarty/compile/'; //编译目录

$smarty->config_dir = __DIR__ . '/../smarty/configs/'; //配置目录

$smarty->cache_dir = __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 = '

$smarty->right_delimiter = '}>'; //右定界符

$smarty->template_dir = __DIR__.'/../view/'; //视图目录

$smarty->compile_dir = __DIR__ . '/../smarty/compile/'; //编译目录

$smarty->config_dir = __DIR__ . '/../smarty/configs/'; //配置目录

$smarty->cache_dir = __DIR__ . '/../smarty/cache/'; //缓存目录

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

我们编写mySmarty类

require '../smarty/Smarty.class.php';

class mySmarty extends Smarty{

public function __construct(array $options = array()){

parent::__construct($options);

$this->debugging = false; //开启debug模式

$this->caching = true; //开启缓存

$this->cache_lifetime = 120; //缓存时间

$this->left_delimiter = '

$this->right_delimiter = '}>'; //右定界符

$this->setTemplateDir(__DIR__.'/../view/'); //视图目录

$this->setCompileDir(__DIR__ . '/../smarty/compile/'); //编译目录

$this->setConfigDir(__DIR__ . '/../smarty/configs/'); //配置目录

$this->setCacheDir(__DIR__ . '/../smarty/cache/'); //缓存目录

}

}

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

require 'mySmarty.php';

$smarty = new mySmarty;

$list = range('A', 'D');

$smarty->assign("list", $list);

$smarty->assign("name", "zhezhao");

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值