欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

TP模版布局Layout改进

程序员文章站 2022-05-15 14:46:38
...
在使用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元