标签:
1,配置文件:config.php
<?php
/**
*@yzt
*TPL_CACHE 用于指定生成.php 的路径(文件)
*TPL_PATH 用于指定生成 模板的文件路径
**/
define(‘TPL_CACHE‘,‘./cache/‘);
define(‘TPL_PATH‘,‘./views/‘);
2,测试 demo1.php
/**
*include 文件导入
*compact 数据数组化
***/
<?php
include ‘config.php‘;
include ‘tpl.func.php‘;
$title = ‘看到女神容易自悲‘;
$content = ‘要想办法拉平你们的关系,不然下手准失败‘;
$footercontent = ‘因为你会扭捏,不自然,女神就会跟你打低分‘;
$data = [
‘yzt‘ => ‘yzt‘,
‘xyy‘ => ‘xyy‘,
];
display(‘moban.html‘,compact(‘title‘,‘content‘,‘data‘,‘footercontent‘));
3,引擎(核心)tpl.func.php
<?php
//两个参数 1,html 模板; 2,需要修改的参数
function display($tplFile, $tplVars = null)
{
$tplFilePath = rtrim(TPL_PATH,‘/‘) . ‘/‘ . $tplFile;
if (!file_exists($tplFilePath)) {
exit(‘模版文件不存在‘);
}
$html = compile($tplFilePath);
$cacheFileName = parsePath($tplFile);
if (!check_cache_dir(TPL_CACHE)) {
exit(‘缓存目录不可写‘);
}
if (!file_put_contents($cacheFileName, $html)) {
exit(‘缓存文件写入失败‘);
}
if (is_array($tplVars)) {
extract($tplVars);
include $cacheFileName;
}
}
function check_cache_dir($path)
{
if(!file_exists($path) || !is_dir($path)) {
return mkdir($path,0755,true);
}
if(!is_writeable($path) || !is_readable($path)) {
return chmod($path,0755);
}
return true;
}
function parsePath($tplFile)
{
$path = rtrim(TPL_CACHE,‘/‘).‘/‘.str_replace(‘.‘,‘_‘,$tplFile).‘.php‘;
return $path;
}
function compile($path)
{
$keys = [
‘{if %%}‘ => ‘<?php if(\1): ?>‘,
‘{else}‘ => ‘<?php else : ?>‘,
‘{else if %%}‘ => ‘<?php elseif(\1) : ?>‘,
‘{elseif %%}‘ => ‘<?php elseif(\1) : ?>‘,
‘{/if}‘ => ‘<?php endif;?>‘,
‘{$%%}‘ => ‘<?=$\1;?>‘,
‘{foreach %%} ‘ => ‘<?php foreach(\1) :?>‘,
‘{/foreach}‘ => ‘<?php endforeach;?>‘,
‘{for %%}‘ => ‘<?php for(\1):?>‘,
‘{/for}‘ => ‘<?php endfor;?>‘,
‘{while %%}‘ => ‘<?php while(\1):?>‘,
‘{/while}‘ => ‘<?php endwhile;?>‘,
‘{continue}‘ => ‘<?php continue;?>‘,
‘{break}‘ => ‘<?php break;?>‘,
‘{$%% = $%%} => ‘<?php $\1 = $\2;?>‘,
‘{$%%++}‘ => ‘<?php $\1++;?>‘,
‘{$%%--}‘ => ‘<?php $\1--;?>‘,
‘{comment}‘ => ‘<?php /* ‘,
‘{/comment}‘ => ‘ */ ?>‘,
‘{/*}‘ => ‘<?php /* ‘,
‘{*/}‘ => ‘* ?>‘,
‘{section}‘ => ‘<?php ‘,
‘{/section}‘ => ‘?>‘,
‘{include %%}‘ => ‘<?php include \1;?>‘,
];
$file = file_get_contents($path);
foreach ($keys as $key => $val) {
$pattern = ‘#‘. str_replace(‘%%‘, ‘(.+)‘, preg_quote($key,‘#‘)) .‘#imsU‘;
$replace = $val;
if (stripos($pattern,‘include‘)) {
$file = preg_replace_callback($pattern, ‘parseInclude‘, $file);
} else{
$file = preg_replace($pattern, $replace, $file);
}
}
return $file;
}
function parseInclude($data)
{
$path = str_replace(array(‘\‘‘,‘"‘),‘‘,$data[1]);
//data[1]就是-------footer.html
$cacheFileName = parsePath($path);
display($path);
return ‘<?php include "‘.$cacheFileName.‘";?>‘;
}
4,模板 moban.html
<html>
<head>
<title>{$title}</title>
</head>
<body>
{$content}
<br />
{foreach $data as $key => $value}
{$key} ------{$value} <br />
{/foreach}
<hr />
<h1>这是这是是这是脚本</h1>
{include footer.html}
</body>
</html>
标签:
原文地址:http://www.cnblogs.com/YZTyzt/p/5774257.html