ThinkCMF&Thinkphp 首页静态化处理

基于TP5的页面静态化教程

1.首页在控制器添加以下代码生成静态页面文件

$info = $this->buildHtml("/staticIndex", 'static', '/index');   //调用

#"/staticIndex"  :   生成静态文件名称

#'static'  :   生成静态文件目录(此目录在public下 需要权限777才能写入)

#'/index'  :   读取源文件

 

public function buildHtml($htmlfile = '', $htmlpath = '', $templateFile = ''){
  //生成静态文件
  $content = $this->fetch($templateFile);
  $htmlpath = !empty($htmlpath) ? $htmlpath : './appTemplate/';
  $htmlfile = $htmlpath . $htmlfile . '.'.config('url_html_suffix');
  $File = new hink emplatedriverFile();
  $File->write($htmlfile, $content);
  return $content;
}

具体操作如下图:

上图是未生成静态文件的控制器 我们官网是分为PC移动端两个模板的  所以PC和移动端都需要

各生成一个静态文件

上图为生成静态页面并输出操作 首次执行应该会报错

解决方法:在public目录下新建static文件夹 并授权777(命令:chmod 777 static) 

上图操作是 判断是否已经生成了静态文件  如果已生成则直接读取静态文件并输出 

更新静态文件只需要修改框架源文件并 删除已生成的静态文件 重新生成即可

$file = "static/staticIndex.html"; //判断PC端首页静态文件是否存在
if(file_exists($file))
  { //存在时直接读取输出静态文件
  $filename = "static/staticIndex.html";
  $handle = fopen($filename, "r");//读取二进制文件时,需要将第二个参数设置成'rb'
  $contents = fread($handle, filesize ($filename));
  return $contents; //pc端
}else{
  //不存在时生成静态文件
  $info = $this->buildHtml("/staticIndex", 'static', '/index');
  // ①生成的静态页名称 ②目录 ③方法名
  dump($info);
}

测速网站:https://www.17ce.com/

*要给static(静态文件目录)加777权限 (命令:chmod 777 static) 

 

 

 

 

 

原文地址:https://www.cnblogs.com/caopeng/p/13544800.html