首页 > php教程 > php手册 > 正文

TP模版布局Layout改进

php中文网
发布: 2016-06-07 11:35:48
原创
2033人浏览过

在使用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元

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号