TP模版布局Layout改进

浏览:6299 发布日期:2016/01/06 分类:系统代码 关键字: 布局 layout
在使用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;
    }
使用实例:
布局文件:<html>
<head>{__HEADER__}</head>
<body>{__CONTENT__}</body>
{__FOOTER__}
</html>
应用:<layout name="布局文件"/>
<placeholder name="HEADER"></placeholder>
<placeholder name="CONTENT"></placeholder>
<placeholder name="FOOTER"></placeholder>
这样,就可以在你的布局文件中定义任意的占位符,方便你在想要的位置插入代码
评论( 相关
后面还有条评论,点击查看>>