Smarty模板引擎的主要用法

PHP中的smarty模板引擎

smarty的核心代码:

1.php文件中的代码:

<?php
class mini
{
    public $data = array();
    public function comp($file)
    {
        //读取文件中的内容赋给 $html 变量
        $html = file_get_contents($file);
        //使用str_replace函数来将网页代码中的{$}替换为<?php echo $this->date['']?>
        $html = str_replace('{$', '<?php echo $this->data[\'', $html);
        $html = str_replace('}','\'];?>', $html);
        //创建一个文件名为$file.php的文件
        $com = $file . '.php';
        //使用 file_put_contents函数来将$html文件中的内容写入到$com文件中。
        file_put_contents($com, $html);
        //再返回到变量$com中去执行。
        return $com;
    }
    public function assign($k,$v){
        $this->data[$k] = $v;
    }

     public function display($file){
        //在本类中使用include去调用上方的comp方法
        include($this->comp($file));
    }
}
$title = "smarty";
$demo = "smarty";

$mini = new mini();
$mini->assign('title',$title);
$mini->assign('demo',$demo);
$mini->assign('ming','maybe you are sure!');
$mini->display('mini.html');

?>

2.这是html文件中的代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>{$title}</h1>
    <h2>{$demo}</h2>
    <h3>{$ming}</h3>
</body>
</html>

运行之后生成一个文件 name.html.php 由此可见smarty的主要功能就是进行前后端的分离,就比如来说前端妹纸看不懂<php echo $a;?>这行代码可以使用smarty来将其转为{$a} 在view端进行展示。

使用smarty,在使用smarty之前要先下载对应的文件下载地址下载并且解压之后将libs文件拷贝到所建项目中。

使用方法:
require '../../libs/Smarty.class.php'; 先使用require函数来引入当前libs文件中的Smarty.class.php文件

然后创建实例化对象$sm = new Smarty(); 接下来就可以使用sm对象去调用smarty模板中的函数了。

smarty中有许多的方法(这里只举例常用的几种函数):

函数功能
assign有两个参数第一个参数是要展示的内容,第二个是在前端调用的变量
display选定展示文件
template_dir设置模板展示路径(优先读取当前文件下的模板)
left_delimiter设置左侧的编译符
right_delimiter设置右侧的编译符
caching开启浏览器缓存
cache_lifetime设置缓存,生命周期单位为秒

这就是smarty模板的主要用法,smarty很少有人使用了已经很少使用了,即使使用也是用来创建自己的模板。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值