Smarty的Include解析我没有看过,这里我贴一个我写的PHP框架的模板引擎里对include的实现吧。
主要也是递归解析,先将解析到的include file="index.tpl"语法,并逐层对其进行解析,最后把解析到的内容插入到include的模板当中。逐层回调后就得到了index.tpl里所有include的内容,不说了,贴上代码吧!
/**
* 解析模板中包含其它模板文件语法 include_tpl
* @param string $content 模板文件内容
* @return void
*/
private function _parseIncludeTpl($content = ''){
if( preg_match_all( $this->_regx_include_tpl, $content, $matchs ) ){
foreach( $matchs[2] as $k => $v){
preg_match_all('/\`\$([\w]*)\`/', $v, $vars);
if($vars){
foreach($vars[1] as $y => $var){
$replace = $this->_tpl_vars[$var];
$v = str_replace( $vars[$y][0], $replace, $v );
}
}
$tplFilePath = str_replace( array("\\", '/'), array(DS, DS), $v );
if( substr($tplFilePath, 0, 1) == DS ){
//采用绝对路径引入模板文件
$tplFilePath = APP_PATH . DS . $this->templateDir . $tplFilePath;
}else{
//采用相对路径引入模板文件
$tplFilePath = dirname($this->templeteFile). DS . $tplFilePath;
}
if( !file_exists($tplFilePath)){
$this->_error('The template file ' . $tplFilePath . ' is not exists!');
}
$includeFileContent = file_get_contents($tplFilePath);
$includeFileContent = $this->_parseIncludeTpl($includeFileContent); //递归include_tpl
$content = str_replace( $matchs[0][$k], $includeFileContent, $content );
}
return $content;
}else{
return $content;
}
}