smarty模板引擎工作原理

版权声明:CopyRight @CSDN 码农Robin https://blog.csdn.net/weixin_41423450/article/details/84428569

1、模板引擎是什么

展示给用户的页面由数据及承载数据的标签组成,标签就是html,而数据就是由php处理的变量,这样就涉及到了前端和后端的交互,模板引擎就是将php代码与html代码分离的技术。
smarty是最常用的php模板引擎,由zend公司使用php编写的一套模板引擎。

2、模板引擎的工作原理

模板引擎的工作原理就是php代码可以嵌套html标签。
在不使用模板引擎的时候,我们可以通过这样的代码来渲染页面:

<?php 
$a = 1;
 ?>
 <?php if($a == 1){ ?>
 <h1><?php echo $a; ?></h1>
 <?php } ?>

而在smarty模板引擎下,则是将文件分离成4部分:

  • php文件:生产数据
  • 模板文件:组织样式
  • 编译文件:对html文档中的smarty标签进行替换后的文件
  • 缓存文件:对编译文件进行执行的结果再保存为一个纯html文档

上面的代码通过smarty来完成,在不开启缓存的情况下,需要创建两个文件,生成一个编译文件:

  • php文件:
<?php
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$a = 1;
$smarty->_assign('a',$a);
$smarty->display('test.html')
 ?>
  • html文件
<h1><{if $a eq 1}><{$a}><{/if}></h1>
  • 编译文件
<h1>?php if($a == 1){ ?><?php echo $a; ?><?php } ?></h1>

3、smarty中常用的方法

  • setTemplateDir()
    用于设置模板目录,在加载模板目录时,smarty会先在设置的模板目录中找模板文件,如果没有设置,则在当前目录下查找
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->setTemplateDir('template');
  • setCompileDir()
    用于设置编译目录,
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->setCompileDir('compile');
  • setCacheDir()
    用于设置缓存目录
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->setCompileDir('template_c');
  • setLeftDelimiter()/setRightDelimiter()
    用于设置左/右边界符
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->setLeftDelimiter('<{');
$smarty->setRightDelimiter('}>');

4、smarty中的缓存

缓存是一个让程序员又爱又恨的东西。它既可以优化项目的性能,改善用户体验,但有时也会引发一些错误,甚至于在调试过程中让程序员花费太多时间在错误的方向上。因此我们更需要清晰地认识缓存。

  • 开启缓存
    smarty默认是没有开启缓存的,需要手动开启。
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->setCacheDir('cache');
$smarty->caching = true;
  • 设置缓存时效
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->setCacheLifetime(60);//单位:秒
  • 局部缓存
    smarty默认是针对模板进行整体缓存,但有时我们需要的是仅缓存公有、不变的部分,这时就需要用到局部缓存了
<{nocache}>
	……
<{/nocache}>

被nocache标签包裹的部分,不会被smarty缓存

  • 变量缓存
    用于将指定变量传递到模板中,当nocached为true时,表示不缓存
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->_assign(name,value【,nocached = false】);
  • 单页面多缓存
    单页面是指一个html模板文件,多缓存生成多个缓存文件。
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->_display(tpl【,cacheid】);

cacheid为对模板文件所产生的缓存文件的唯一标识

  • 判断缓存
    用于判断指定的模板文件是否以给定的cacheid生成缓存文件。在调用此方法前必须开启缓存,才能进行判断
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->isCached(tpl【,cacheid】);
  • 删除缓存
    删除指定的模板的缓存文件,如果指定cacheid,则只删除给定的缓存id的那个缓存文件。
include 'smarty/smarty.class.php';
$smarty = new Smarty();
$smarty->clearCache(tpl【,cacheid】);

猜你喜欢

转载自blog.csdn.net/weixin_41423450/article/details/84428569
今日推荐