百搜论坛欢迎您的加入!
adimg adimg
 
昨日:篇  今日:篇   总帖:篇   会员:
博主最大Lv63   
smarty模板的使用方法实例分析     

[导读] smarty模板的使用方法实例分析...

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

这里以smarty3为例

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

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

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

Image

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

index.php

1

2

3

4

5

6

7

8

9

10

11

12

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

1

$v }> :

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

解决方法有两种:

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

1

2

3

4

5

6

7

8

9

10

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类

1

2

3

4

5

6

7

8

9

10

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代码可优化为:

1

2

3

assign("list"$list);

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

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

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

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

 0  已被阅读了1338次  楼主 2020-07-06 13:32:06
回复列表

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

联系站长 友链申请桂ICP备19000949号-1     桂ICP备19000949号-1
您的IP:3.146.65.212,2024-04-19 11:39:52,Processed in 0.02017 second(s).
免责声明: 本网不承担任何由内容提供商提供的信息所引起的争议和法律责任。
Powered by HadSky 7.12.9
已有0次打赏
(0) 分享
分享
取消
免责声明
1、本站资源,均来自网络,版权归原作者,所有资源和文章仅限用于学习和研究目的 。
2、不得用于商业或非法用途,否则,一切责任由该用户承担 !
如果觉得本文还不错请点个赞或者打赏点轻币哦~
拒绝伸手党,拿走请回复,尊重楼主,尊重你我他~

侵权删除请致信 E-Mail:207882320@qq.com