认识smarty

简介:

smarty就是一个类

image

image

image

例1:自定义smarty搜索引擎,认识smarty

image

image

image

这段正则表达式:\s*表空格,{}需要转义  ([a-zA-Z_][a-zA-Z0-9_]*)  以字母或者下划线开始,后面可以是字母数字下划线,*0或多个字符

生成的组合文件:

image

显示的结果:

image

源代码:如下

sm.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">    
<html>    
<head>    
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
<title>{$title}</title>    
</head>    
<body>    
<div> {$xx}</div>    
<div> {$xx}</div>    
  <div> {$title}</div>    
  <div> {$xx}</div>    
<div> {$xx}</div>    
  <div> {$xx}</div>

</body>   
</html>

sm.php

<?php   
include "smarty.class.php";

$sm = new smarty();

//例如:连接数据库,获取以下内容;   
$tt = " this is article title";    
$xinxi = "this is the article content";

$sm ->assign("title",$tt);   
$sm ->assign("xx",$xinxi);    
$sm ->display("sm.html");    
//var_dump($sm);

smarty.class.php

<?php   
class  smarty{    
    private $vars=array();    
    function assign($key,$value)    
    {    
        $this->vars[$key] = $value;    
    }    
    function display($tplfile)    
    {   
          $tfile ="./tpls/".$tplfile;    
          $comfile = "./coms/com_".$tplfile.".php";    
          if(!file_exists($comfile) || filemtime($comfile) < filemtime($tfile) )    
          {    
            $content = file_get_contents($tfile);    
            $pattern =array(    
                  '/\{\s*\$([a-zA-Z_][a-zA-Z0-9_]*)\s*\}/'    
                  );    
            $replacement = array(    
                  '<?php  echo $this->vars["${1}"];  ?>'    
              );    
            $newcontent = preg_replace($pattern, $replacement, $content);    
            file_put_contents($comfile,$newcontent);    
         }    
          include $comfile;    
    }    
}



本文转自 gjp0731 51CTO博客,原文链接:http://blog.51cto.com/guojiping/1565630

相关文章
|
9月前
|
PHP
php模版引擎smarty出现Undefined index的解决方案
php模版引擎smarty出现Undefined index的解决方案
66 0
|
Web App开发 PHP 索引
smarty、smarty格式化、smarty整数、smarty float、smarty各种转换方式、smarty日期转换等等
smarty code: {config_load file='config.conf'} Smarty学习 {capture name=banner}{*注释掉中间显示内容*} {include file="banner.
1235 0
|
PHP 索引
smarty手册-smarty中foreach循环语句详解
原文地址:smarty手册-smarty中foreach循环语句详解作者:谭博 {foreach}循环也有自身属性的变量,可以通过{$smarty.foreach.name.property}访问,其中"name"是name属性。
1185 0
|
PHP 前端开发 网络架构
|
编解码 JavaScript 前端开发