在使用layout布局时,tp只提供了替换单一占位__content__布局。如果想要临时加点内容到特殊位置,那就得另外定义一个布局文件。本人在原基础上增加了占位符解析。可以方便在想要的位置插入代码
在使用layout布局时,tp只提供了替换单一占位__content__布局。如果想要临时加点内容到特殊位置,那就得另外定义一个布局文件。本人在原基础上增加了占位符解析。可以方便在想要的位置插入代码。tp原布局方式仍然可用。具体代码如下//修改替换thinkphp/library/think/template模版类中的parselayout布局解析方法
//使用正则匹配placeholder区域,并替换placeholder特性name所指定的在布局中的占位
//占位格式:{__占位名__}
protected function parselayout($content) {
// 读取模板中的布局标签
$find = preg_match('/'.$this->config['taglib_begin'].'layout\s(.+?)\s*?\/'.$this->config['taglib_end'].'/is',$content,$matches);
if($find) {
//替换layout标签
$content = str_replace($matches[0],'',$content);
//解析layout标签
$array = $this->parsexmlattrs($matches[1]);
if(!c('layout_on') || c('layout_name') !=$array['name'] ) {
// 读取布局模板
$layoutfile = theme_path.$array['name'].$this->config['template_suffix'];
$pattern='/'.$this->config['taglib_begin'].'placeholder\s([^'.$this->config['taglib_end'].']*?)'.$this->config['taglib_end'].'\s(.+?)\s*?'.$this->config['taglib_begin'].'\/placeholder'.$this->config['taglib_end'].'/is';
$result= preg_match_all($pattern,$content,$matches);
if($result){
$layout=file_get_contents($layoutfile);
foreach($matches[0] as $index=>$placeholder){
$array=$this->parsexmlattrs($matches[1][$index]);
$replace='{__'.$array[name].__};
$layout = str_replace($replace,$matches[2][$index],$layout);
}
$content=$layout;
}else{
$replace = isset($array['replace'])?$array['replace']:$this->config['layout_item'];
// 替换布局的主体内容
$content = str_replace($replace,$content,file_get_contents($layoutfile));
}
//替换掉模版中空的占位
$content=preg_replace('/{__\w+?__}/','',$content);
}
}else{
$content = str_replace('{__nolayout__}','',$content);
}
return $content;
}使用实例:
布局文件:
{__header__}
{__content__}
{__footer__}
应用:
这样,就可以在你的布局文件中定义任意的占位符,方便你在想要的位置插入代码
ad:真正免费,域名+虚机+企业邮箱=0元