码迷,mamicode.com
首页 > 其他好文 > 详细

迷你版smarty的制作,模板制作流程,方法,思想

时间:2015-09-13 18:43:25      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

 smarty模板引擎是为了分离php代码和html代码;

原理:分析html模板中的标签,生成相应的php文件,再引入该php

访问过程: 1、用户访问.php文件:在php文件中包含模板文件,传递模板文件中的一些必要属性

/**
 * 总结:
 * $smarty的工作流程;
 * 1、把需要显示的全局变量赋值,塞到对象内部的属性上,一个数组里
 * 2、编译模板,把{$标签},解析成相应的PHPecho代码
 * 3、引入编译后的php文件
 *
 *
 * 使用smarty的步骤
 * 1、smarty是一个类,要使用,需要先引入并实例化
 * 2、assign赋值
 * 3、display[编译到输出]
 *
 * smarty之辩
 * 1、编译模板,浪费时间
 * 2、要把变量再重新赋值到对象的属性,增大开销
 */

1、访问的页面

demo.php

<?php
include ‘./mini.php‘;

$mini=new mini();

$mini->template_dir=‘./template‘;
$mini->compile_dir=‘./compile‘;
//echo $mini->compile(‘01.html‘);
$title=‘霍‘;
$content=‘,hello‘; 

$mini->assign(‘title‘, $title);
$mini->assign(‘content‘, $content);

//print_r($mini->_tpl_var);
//include $mini->compile("01.html");
$mini->display(‘01.html‘);

2、需要引入的模板引擎

<?php
class mini{
    public $template_dir=‘‘;//模板文件所在的位置
    public $compile_dir=‘‘;//模板编译后存放的位置
    //定义一个数组,用来接收外部的变量
    public $_tpl_var=array();
    
    public function assign($key,$value){
        $this->_tpl_var[$key]=$value;
    }
    /*
     * string $temlate 模板文件名
     * return string
     * 流程:把指定的模板内容读过来,再编译成PHP
     * */
    public function display($template){
        $comp=$this->compile($template);
        include $comp;
    }
    /*
     * string $temlate 模板文件名
     * return string
     * 流程:把指定的模板内容读过来,再编译成PHP
     * */
    public function compile($template){
        
        $temp=$this->template_dir.‘/‘.$template;//模板文件
        $comm=$this->compile_dir.‘/‘.$template.‘.php‘;//编译后文件
        
        //判断模板文件是否存在
        if(file_exists($comm) && filemtime($temp)<filemtime($comm)){
            return $comm;
        }
        //读出模板内容
        $source=file_get_contents($temp);
        //替换模板内容
        $source=str_replace(‘{$‘, ‘<?php echo $this->_tpl_var[\‘‘, $source);
        $source=str_replace(‘}‘,‘\‘]; ?>‘, $source);
        //把编译后的内容保存成.php文件

        file_put_contents($comm, $source);
        return $comm;
    }
}

 

迷你版smarty的制作,模板制作流程,方法,思想

标签:

原文地址:http://www.cnblogs.com/hhfhmf/p/4805301.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!