Home php教程 php手册 模板引擎?No 正则而已

模板引擎?No 正则而已

Jun 06, 2016 pm 07:35 PM
engine template regular

之前就觉得TP的那个模板引擎太不爽了,非常的蛋疼,所以参照PHPCMS的改了下,哈哈,自己看吧 无 /** * 模板函数 * @param string $template 模板文件名 * @param string $path 模板路径 * @param string $suffix 模板后缀 */function template($template = '', $p

之前就觉得TP 的那个模板引擎太不爽了,非常的蛋疼,所以参照PHPCMS的 改了下, 哈哈,自己看吧
/**
 * 模板函数
 * @param string $template 模板文件名
 * @param string $path  模板路径
 * @param string $suffix 模板后缀
 */
function template($template = '', $path = '', $suffix = '', $show_error = true) {
    $tpl_path = $path ? $path : (config('tpl_path') ? config('tpl_path') : './template/');
    $tpl_suffix = $suffix ? $suffix : (config('tpl_suffix') ? config('tpl_suffix') : '.html');
    if (empty($template)) {
        $template_file = $tpl_path . __MODULE__ . '/' . __CONTROLLER__ . '/' . __ACTION__;
    } else {
        if (!$path) {
            $pcount = substr_count($template, '/');
            if ($pcount == 0) {
                $template_file = $tpl_path . __MODULE__ . '/' . __CONTROLLER__ . '/' . trim($template, '/');
            } else if ($pcount == 1) {
                $template_file = $tpl_path . __MODULE__ . '/' . trim($template, '/');
            } else {
                $template_file = $tpl_path . trim($template, '/');
            }
        } else {
            $template_file = $path . trim($template, '/');
        }
    }
    $template_file .= $tpl_suffix;
    if (!is_file($template_file)) {
        if ($show_error === true) {
            halt('模板文件不存在:' . $template_file);
        }
    } else {
        $cache_template = DATA_PATH . 'cache' . _DIR . 'template' . _DIR . __MODULE__ . _DIR . md5($template_file) . '.php';
        if (is_file($cache_template) && config('tpl_cache') == true && (config('tpl_expire') == 0 || (@filemtime($cache_template) + config('tpl_expire')) < time())) {
            
        } else {
            template::template_compile($template_file, $cache_template);
        }
        return $cache_template;
    }
}
Copy after login
<?php

class template {

    /**
     * 编译模板
     * @param string  $template_file 模板文件
     * @param string $cache_file 缓存文件
     */
    public static function template_compile($template_file, $cache_file) {
        if (!is_file($template_file)) {
            return false;
        }
        $content = file_get_contents($template_file);
        $cache_dir = dirname($cache_file);
        if (!is_dir($cache_dir)) {
            mkdir($cache_dir, 0777, true);
        }
        $content = self::parse_template($content);
        @file_put_contents($cache_file, $content);
        return $cache_file;
    }

    public static function parse_template($str) {
        //include
        $str = preg_replace("/\{template\s+(.+)\}/", "<?php include template(\\1,'','','',false); ?>", $str);
        $str = preg_replace("/\{include\s+(.+)\}/", "<?php include \\1; ?>", $str);        
        
        $str = preg_replace("/\{php\s+(.+?)\}/", "<?php \\1?>", $str);
        $str = preg_replace("/\{!(.+?)\}/", "<?php \\1?>", $str);
        $str = preg_replace("/\{if\s+(.+?)\}/", "<?php if(\\1) { ?>", $str);
        $str = preg_replace("/\{else\}/", "<?php } else { ?>", $str);
        $str = preg_replace("/\{elseif\s+(.+?)\}/", "<?php } elseif (\\1) { ?>", $str);
        $str = preg_replace("/\{\/if\}/", "<?php } ?>", $str);
        //for
        $str = preg_replace("/\{for\s+(.+?)\}/", "<?php for(\\1) { ?>", $str);
        $str = preg_replace("/\{\/for\}/", "<?php } ?>", $str);
        //++ --         
        $str = preg_replace("/\{\+\+(.+?)\}/", "<?php ++\\1; ?>", $str);
        $str = preg_replace("/\{\-\-(.+?)\}/", "<?php ++\\1; ?>", $str);
        $str = preg_replace("/\{(.+?)\+\+\}/", "<?php \\1++; ?>", $str);
        $str = preg_replace("/\{(.+?)\-\-\}/", "<?php \\1--; ?>", $str);
        //loop
        $str = preg_replace("/\{loop\s+(\S+)\s+(\S+)\}/", "<?php \$n=1;if(is_array(\\1)) foreach(\\1 AS \\2) { ?>", $str);
        $str = preg_replace("/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}/", "<?php \$n=1; if(is_array(\\1)) foreach(\\1 AS \\2 => \\3) { ?>", $str);
        $str = preg_replace("/\{\/loop\}/", "<?php \$n++;}unset(\$n); ?>", $str);
        //函数
        $str = preg_replace("/\{:([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str);
        $str = preg_replace("/\{~([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php \\1;?>", $str);
        //变量
        
        $str = preg_replace("/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str);
        $str = preg_replace("/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/", "<?php echo \\1;?>", $str);
        $str = preg_replace("/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\->[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:])\}/", "<?php echo \\1;?>", $str);
        $str = preg_replace("/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|([^{}]*)\}/", "<?php if(!empty(\\1)){echo \\1;}else{echo \\2;}?>", $str);
        $str = preg_replace('/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\->)[^\}]+)\}/',"<?php echo \\1;?>", $str);
        
        //数组
        $str = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\}/es", "self::addquote('<?php echo \\1;?>')", $str);
        $str = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\|([^{}]*)\}/es", "self::addquote('<?php if(!empty(\\1)){echo \\1;}else{echo \\2;} ?>')", $str);

        //常量
        $str = preg_replace("/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/s", "<?php echo \\1;?>", $str);
        //扩展标签
        $str = preg_replace("/\{tag:(\w+)\s+([^}]+)\}/ie", "self::tag('$1','$2')", $str);
        $str = preg_replace("/\{:tag:(\w+)\s+([^}]+)\}/ie", "self::tag('$1','$2',true)", $str);
        return $str;
    }

    public static function addquote($var) {
        return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));
    }

    public static function tag($name, $data, $echo = false) {
        preg_match_all("/([a-z]+)\=[\"]?([^\"]+)[\"]?/i", stripslashes($data), $matches, PREG_SET_ORDER);

        foreach ($matches as $v) {
            if (in_array($v[1], array('action', 'cache', 'return'))) {
                $$v[1] = $v[2];
                continue;
            }

            $datas[$v[1]] = $v[2];
        }
        if (!isset($action) || empty($action)) { //方法
            return false;
        }
        if (isset($cache)) { //缓存
            $cache = intval($cache);
        } else {
            $cache = false;
        }
        if (!isset($return) || empty($return)) {
            $return = '$data';
        }
        $tag_file = EXT_PATH . 'tags' . _DIR . $name . '_tag' . EXT;
        if (!is_file($tag_file)) {
            return false;
        }
        $str = '<?php ';
        if ($cache !== false) {
            $cache_name =  'tag/'.$name.'_'.$action.  to_guid_string($datas);
            $str .= '$cache = cache::getInstance();';
            $str .= $return . '=$cache->get("' . $cache_name . '");';
            $str .= 'if(' . $return . ' === false){';
            $str .= '$params = ' . self::filter_var($datas) . ';';
            $str .= '$tag = load_ext("tags/' . $name . '_tag",true);';
            $str .= $return . '=$tag->' . $action . '($params);';
            $str .= '$cache->set("' . $cache_name . '",' . $return . ',' . $cache . ');';
            $str .= '}';
            if ($echo == true) {
                $str .= 'echo ' . $return . ';';
            }
            $str .= ' ?>';
        } else {

            $str .= '$params = ' . self::filter_var($datas) . ';';
            $str .= '$tag = load_ext("tags/' . $name . '_tag",true);';
            if ($echo) {
                $str .= 'echo $tag->' . $action . '($params);';
            } else {
                $str .= $return . '=$tag->' . $action . '($params);';
            }
            $str .= ' ?>';
        }
        return $str;
    }

    protected static function filter_var($data) {
        $str = var_export($data, true);
        //$str = preg_replace('/\'\$(\w+?)\'/', "\$\\1", $str);
        $str = preg_replace('/\'/', '"', $str);
        $str = preg_replace('/\s{2,}/', '', $str);
        return $str;
    }

}
Copy after login
public function test(){ 
    include template();        
}
Copy after login
{if !empty($result)}
				{loop $result $r}
				<tr>
					<td>{$r['order_sn']}</td>
					<td>{$r['name']}</td>
					<td>{$r['mobile']}</td>
					<td>{:fdate($r['add_time'])}</td>
					<td>{if $r['status'] == 0}处理中{elseif $r['status'] ==1}已处理{else}无效{/if}</td>
				</tr>
				{/loop}
				{else}
				<tr>
					<td colspan="9">
						<span style="padding:10px; display:block;">您还没有收到任何预约</span>
					</td>
				</tr>
				{/if}
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to replace a string starting with something with php regular expression How to replace a string starting with something with php regular expression Mar 24, 2023 pm 02:57 PM

PHP regular expressions are a powerful tool for text processing and conversion. It can effectively manage text information by parsing text content and replacing or intercepting it according to specific patterns. Among them, a common application of regular expressions is to replace strings starting with specific characters. We will explain this as follows

How to match multiple words or strings using Golang regular expression? How to match multiple words or strings using Golang regular expression? May 31, 2024 am 10:32 AM

Golang regular expressions use the pipe character | to match multiple words or strings, separating each option as a logical OR expression. For example: matches "fox" or "dog": fox|dog matches "quick", "brown" or "lazy": (quick|brown|lazy) matches "Go", "Python" or "Java": Go|Python |Java matches words or 4-digit zip codes: ([a-zA

How to add PPT mask How to add PPT mask Mar 20, 2024 pm 12:28 PM

Regarding PPT masking, many people must be unfamiliar with it. Most people do not understand it thoroughly when making PPT, but just make it up to make what they like. Therefore, many people do not know what PPT masking means, nor do they understand it. I know what this mask does, and I don’t even know that it can make the picture less monotonous. Friends who want to learn, come and learn, and add some PPT masks to your PPT pictures. Make it less monotonous. So, how to add a PPT mask? Please read below. 1. First we open PPT, select a blank picture, then right-click [Set Background Format] and select a solid color. 2. Click [Insert], word art, enter the word 3. Click [Insert], click [Shape]

How to use regular expressions to remove Chinese characters in php How to use regular expressions to remove Chinese characters in php Mar 03, 2023 am 10:12 AM

How to remove Chinese in PHP using regular expressions: 1. Create a PHP sample file; 2. Define a string containing Chinese and English; 3. Use "preg_replace('/([\x80-\xff]*)/i', '',$a);" The regular method can remove Chinese characters from the query results.

Effects of C++ template specialization on function overloading and overriding Effects of C++ template specialization on function overloading and overriding Apr 20, 2024 am 09:09 AM

C++ template specializations affect function overloading and rewriting: Function overloading: Specialized versions can provide different implementations of a specific type, thus affecting the functions the compiler chooses to call. Function overriding: The specialized version in the derived class will override the template function in the base class, affecting the behavior of the derived class object when calling the function.

PHP email templates: customize and personalize your email content. PHP email templates: customize and personalize your email content. Sep 19, 2023 pm 01:21 PM

PHP email templates: Customize and personalize your email content With the popularity and widespread use of email, traditional email templates can no longer meet people's needs for personalized and customized email content. Now we can create customized and personalized email templates by using PHP programming language. This article will show you how to use PHP to achieve this goal, and provide some specific code examples. 1. Create an email template First, we need to create a basic email template. This template can be an HTM

How to use templates in OneNote to improve productivity How to use templates in OneNote to improve productivity Apr 30, 2023 am 11:31 AM

Did you know that using templates can make you faster at note-taking and more effective at capturing important ideas? OneNote has a set of ready-made templates for you to use. The best part is that you can also design the template according to your needs. Whether you are a student, a corporate warrior or a freelancer doing creative work. OneNote templates can be used to record important notes in a structure and format that suits your style. A template can be an outline of a note-taking process. Amateurs just take notes, professionals take notes and draw connections from them through well-structured notes with the help of templates. Let's see how to use templates in OneNote. Use Default OneNote Template Step 1: Press Windows+R on your keyboard. Type Oneno

Engine landscape changes: Three-cylinder engines challenge the dominance of six-cylinders and eight-cylinders Engine landscape changes: Three-cylinder engines challenge the dominance of six-cylinders and eight-cylinders Oct 08, 2023 pm 10:57 PM

According to news on October 8, the U.S. auto market is undergoing a change under the hood. The previously beloved six-cylinder and eight-cylinder power engines are gradually losing their dominance, while three-cylinder engines are emerging. News on October 8 showed that the U.S. auto market is undergoing a change under the hood. The beloved six-cylinder and eight-cylinder power engines in the past are gradually losing their dominance, and the three-cylinder engine is beginning to emerge. In most people's minds, Americans love large-displacement models, and the "American big V8" has always been the Synonymous with American cars. However, according to data recently released by foreign media, the landscape of the U.S. auto market is undergoing tremendous changes, and the battle under the hood is intensifying. It is understood that before 2019, the United States

See all articles