天天看点

tp5 生成静态页面代码

//写入
    /***
    $filepath 生成静态文件路径
    $tpl 模板文件名称
    ***/
	private function filePutContents($filepath,$tpl){
		ob_start();
		$content = $this->fetch('[email protected]/'.$tpl); 
        //模板渲染路径['[email protected]/'.$tpl]  表示: /app/index/view/index/index.html
		echo $content;
		$_cache=ob_get_contents();
		ob_end_clean();
		if($_cache){
			$File = new \think\template\driver\File();
			$File->write($filepath, $_cache);
		}
	}

    //调用    
    public function createhtml(){
        //渲染前调用你首页模块的控制器方法。这样模板里面才有数据显示 
        action('index/index/doindex',array('type'=>1)); 
        $this->filePutContents('./index.html','index');
    }
           

注意事项:

1、模板必须放在index/view/ 下面,我试过把模板分享到最外层发现报错了。不知道还有没有其他方法

2、模板自定义输出标签放在extend里面,我发现放在common 里面生成静态标签不解析。

      例如:extend/taglib/Mytag.php ,这里在配置文件app/config.php 里面这样调用      

//预加载模板标签
	'template'=>[
        'taglib_pre_load'  => 'taglib\Mytag',
        'taglib_build_in'  =>  'cx,taglib\Mytag'
    ]
           

3、模板目录资源文件路径__PUBLIC__也可放在extend 里面,作为行为。 替换模板里面路径。

      例如:extend/hook/FilterMb.php

<?php

namespace hook;

use think\Request;

/**
 * 视图输出过滤
*/
class FilterMb
{

    /**
     * 当前请求对象
     * @var Request
     */
    protected $request;

    /**
     * 行为入口
     * @param $params
     */	 
    public function run(&$params)
    {		
        $this->request = Request::instance();
        $appRoot = $this->request->root(true);
        $replace = [
            '__APP__'    => $appRoot,
            '__SELF__'   => $this->request->url(true),
            '__PUBLIC__' => strpos($appRoot, EXT) ? ltrim(dirname($appRoot), DS) : $appRoot,
        ];
        $params = str_replace(array_keys($replace), array_values($replace), $params);
    }

  
}
           

在app下面新建一个tags.php  里面内容为

<?php

return [
    // 应用初始化
    'app_init'     => [],
    // 应用开始
    'app_begin'    => [],
    // 模块初始化
    'module_init'  => [],
    // 操作开始执行
    //'action_begin' => [],
    // 视图内容过滤
    'view_filter'  => ['hook\\FilterMb'],
    // 日志写入
    'log_write'    => [],
    // 应用结束
    'app_end'      => [],
	
	];



           

4.模板里面获取资源例如放在static/index/css/style.css   

<link href="__PUBLIC__/static/index/css/style.css?v={:time()}" target="_blank" rel="external nofollow"  rel="stylesheet" type="text/css">
           

5.模板里面调用代公共模板需写成

{include file="[email protected]/head"}
           

当然这也是我参考别人框架写的,确实写得可以,已经实现了。如果大家有什么不明白可以加我QQ:564379992  ,当时搞了好几天,确实花了不少时间。

可能说得不是很清楚,望见凉,我只是将我知道的分享出来,免得大家像我一样不知道怎么下手,少走弯路。

推荐全站真静态 TP5CMS 系统,hsycms v3.1 连接  http://www.hsycms.com

TP5生成静态页面DEMO源码:https://gitee.com/sywlgzs/tp5html