uchome的模板处理主要调用/source目录下的function_template.php文件中的parse_template函数实现(比起smarty可真是超轻量级了).
解析过程并不复杂,主要是读取模板文件(.htm),用规则表达式替换标记为PHP标准语法,最终生成一个标准的PHP文件,保存到缓存目录
1:读入模板文件,模板文件一般在template/default下面
Code
//read
if(!file_exists($tplfile)) {
$tplfile = str_replace('/'.$_SCONFIG['template'].'/', '/default/', $tplfile);
}
$template = sreadfile($tplfile);
if(emptyempty($template)) {
exit("Template file : $tplfile Not found or have no access!");
}
2:对模板标记解析
变量:
Code
$var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9_\-\.\"\'\[\]\$\x7f-\xff]+\])*)";
$template = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $template);
$template = preg_replace("/([\n\r]+)\t+/s", "\\1", $template);
$template = preg_replace("/(\\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\.([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/s", "\\1['\\2']", $template);
$template = preg_replace("/\{(\\\$[a-zA-Z0-9_\[\]\'\"\$\.\x7f-\xff]+)\}/s", "<?=\\1?>", $template);
$template = preg_replace("/$var_regexp/es", "addquote('<?=\\1?>')", $template);
$template = preg_replace("/\<\?\=\<\?\=$var_regexp\?\>\?\>/es", "addquote('<?=\\1?>')", $template);
逻辑解析:
Code
//逻辑
$template = preg_replace("/\{elseif\s+(.+?)\}/ies", "stripvtags('<?php } elseif(\\1) { ?>','')", $template);
$template = preg_replace("/\{else\}/is", "<?php } else { ?>", $template); 循环和常量
//循环
Code
for($i = 0; $i < 5; $i++) {
$template = preg_replace("/\{loop\s+(\S+)\s+(\S+)\}(.+?)\{\/loop\}/ies", "stripvtags('<?php if(is_array(\\1)) { foreach(\\1 as \\2) { ?>','\\3<?php } } ?>')", $template);
$template = preg_replace("/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}(.+?)\{\/loop\}/ies", "stripvtags('<?php if(is_array(\\1)) { foreach(\\1 as \\2 => \\3) { ?>','\\4<?php } } ?>')", $template);
$template = preg_replace("/\{if\s+(.+?)\}(.+?)\{\/if\}/ies", "stripvtags('<?php if(\\1) { ?>','\\2<?php } ?>')", $template);
}
//常量
$template = preg_replace("/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/s", "<?=\\1?>", $template); 3:最后写入到/data/tpl_cache/目录下
//write
if(!swritefile($objfile, $template)) {
exit("File: $objfile can not be write!");
}