php教程 php手册 从康盛产品(discuz)提取出来的模板类

从康盛产品(discuz)提取出来的模板类

Jun 21, 2016 am 08:54 AM
gt replace template this

复制代码 代码如下:


/*template.class.php
@康盛微博 模板提取类 觉得这个模板好用 花些时间独立出来。 by 雷日锦
@看了一下ctt 这个模板 跟 phpcms的模板类似 难道?? ^_^ 嘿嘿!!!
@ 微博 http://weibo.com/lrjxgl
@ 好东西大家共享 磕磕绊绊的提取出来 有问题请提出来
@ 模板文件默认为 .htm
$tpl = new template('skin',"default");
$tpl->objdir='tpp';
$tpl->rewrite=true;//开启rewrite 需要服务器支持
$tpl->rewrite_rule=array(array("/index\.php/"),array("index.html")); //rewrite规则
$tpl->assign("indexurl","index.php");
$tpl->assign("str","我是字符串啦啦啦");
$tpl->assign("ec","我是被echo出来的");
$tpl->assign("subhtml","{subtpl ttt}这是用来引入一个模板文件的,这个就是引入ttt.htm");
$tpl->assign("a",array('dasdasd'.'bbbbbbb','cccccccccccccc'));
$tpl->assign("i",1);
$tpl->display("index");
*/
if(!defined("CHARSET")) define("CHARSET","gb2312");//字符编码
if(!defined("DIR_TPL")) define("DIR_TPL","tpl");//默认模板目录
if(!defined("DIR_DATA")) define("DIR_DATA","data");//默认数据目录
if(!defined("DEBUG")) define("DEBUG",0);//默认运行模式
class template {
//note var
public $rewrite=false;//是否开启 伪静态 rewrite
public $rewrite_rule=array(); //设置伪静态规则
public $defaulttpldir;//默认的模板
public $tpldir;//模板目录
public $objdir;//编译缓存目录
public $tplfile;//模板文件
public $objfile;//编译文件
public $tplid=1;//模板编号
public $currdir='default';//当前风格目录
public $vars=array();//note 变量表
public $removeblanks=false;//移除空格
public $stdout='display';//输出类型
function __construct($tplid, $currdir) {
$this->template($tplid, $currdir);
}
function template($tplid, $currdir) {
ob_start();
if(file_exists(DIR_TPL.'/'.$currdir)) {
$this->currdir = $currdir;
$this->tplid = $tplid;
} else {
$this->currdir = 'default';
$this->tplid = 1;
}
$this->defaulttpldir = DIR_TPL.'/default';
$this->tpldir = DIR_TPL.'/'.$this->currdir;
$this->objdir = DIR_DATA.'/cache/tpl';
if(version_compare(PHP_VERSION, '5') == -1) {
register_shutdown_function(array(&$this, '__destruct'));
}
}
//note publlic
function assign($k, $v) {
$this->vars[$k] = $v;
}
//note publlic
function display($file) {
extract($this->vars, EXTR_SKIP);
include $this->getObj($file);
}
function getObj($file, $tpldir = '') {
$subdir = ($pos = strpos($file, '/')) === false ? '' : substr($file, 0, $pos);
$file = $subdir ? substr($file, $pos + 1) : $file;
$this->tplfile = ($tpldir ? $tpldir : $this->tpldir).'/'.($subdir ? $subdir.'/' : '').$file.'.htm';
$this->objfile = $this->objdir.'/'.($tpldir ? '' : $this->tplid.'_').($subdir ? $subdir.'_' : '').$file.'.php';
//note 默认目录
if(@filemtime($this->tplfile) === FALSE) {
$this->tplfile = $this->defaulttpldir.'/'.($subdir ? $subdir.'/' : '').$file.'.htm';
}
//note 判断是否比较过期
if(!file_exists($this->objfile) DEBUG && @filemtime($this->objfile) tplfile)) {
$this->compile();
}
return $this->objfile;
}
function getTpl($file) {
$subdir = ($pos = strpos($file, '/')) === false ? '' : substr($file, 0, $pos);
$file = $subdir ? substr($file, $pos + 1) : $file;
$tplfile = $this->tpldir.'/'.($subdir ? $subdir.'/' : '').$file.'.htm';
if(@filemtime($tplfile) === FALSE) {
$tplfile = $this->defaulttpldir.'/'.($subdir ? $subdir.'/' : '').$file.'.htm';
}
return $tplfile;
}
function compile() {
$var_regexp = "\@?\\\$[a-zA-Z_]\w*(?:\[[\w\.\"\'\[\]\$]+\])*";
$vtag_regexp = "\";
$const_regexp = "\{([\w]+)\}";
$template = file_get_contents($this->tplfile);
for($i = 1; $i if(strpos($template, '{subtpl') !== FALSE) {
if(DEBUG == 2) {
$template = str_replace('{subtpl ', '{tpl ', $template);
} else {
$template = preg_replace("/[\n\r\t]*\{subtpl\s+([a-z0-9_:\/]+)\}[\n\r\t]*/ies", "file_get_contents(\$this->getTpl('\\1'))", $template);
}
}
}
$remove = array(
'/(^\r\n)\/\*.+?(\r\n)\*\/(\r\n)/is',
'/\/\/note.+?(\r\n)/i',
'/\/\/debug.+?(\r\n)/i',
'/(^\r\n)(\s\t)+/',
'/(\r\n)/',
);
$this->removeblanks && $template = preg_replace($remove, '', $template);
$template = preg_replace("/\/s", "{\\1}", $template);
$template = preg_replace("/\{($var_regexp)\}/", "=\\1?>", $template);
$template = preg_replace("/\{($const_regexp)\}/", "=\\1?>", $template);
$template = preg_replace("/(?", $template);
$template = preg_replace("/\/ies", "\$this->arrayindex('\\1', '\\2')", $template);
$template = preg_replace("/\{\{eval (.*?)\}\}/ies", "\$this->stripvtag(' \\1?>')", $template);
$template = preg_replace("/\{eval (.*?)\}/ies", "\$this->stripvtag(' \\1?>')", $template);
$template = preg_replace("/[\n\r\t]*\{echo\s+(.+?)\}[\n\r\t]*/ies", "\$this->stripvtag(' echo \\1; ?>','')", $template);
$template = preg_replace("/\{for (.*?)\}/ies", "\$this->stripvtag(' for(\\1) {?>')", $template);
$template = preg_replace("/\{elseif\s+(.+?)\}/ies", "\$this->stripvtag(' } elseif(\\1) { ?>')", $template);
for($i=0; $i$template = preg_replace("/\{loop\s+$vtag_regexp\s+$vtag_regexp\s+$vtag_regexp\}(.+?)\{\/loop\}/ies", "\$this->loopsection('\\1', '\\2', '\\3', '\\4')", $template);
$template = preg_replace("/\{loop\s+$vtag_regexp\s+$vtag_regexp\}(.+?)\{\/loop\}/ies", "\$this->loopsection('\\1', '', '\\2', '\\3')", $template);
}
$template = preg_replace("/\{if\s+(.+?)\}/ies", "\$this->stripvtag(' if(\\1) { ?>')", $template);
$template = preg_replace("/\{tpl\s+(\w+?)\}/is", " include \$this->getObj(\"\\1\");?>", $template);
$template = preg_replace("/\{tpl\s+(.+?)\}/ise", "\$this->stripvtag(' include \$this->getObj(\"\\1\"); ?>')", $template);
$template = preg_replace("/\{tmptpl\s+(\w+?)\}/is", " include \$this->getObj(\"\\1\", \$this->objdir);?>", $template);
$template = preg_replace("/\{tmptpl\s+(.+?)\}/ise", "\$this->stripvtag(' include \$this->getObj(\"\\1\", \$this->objdir); ?>')", $template);
$template = preg_replace("/\{else\}/is", " } else { ?>", $template);
$template = preg_replace("/\{\/if\}/is", " } ?>", $template);
$template = preg_replace("/\{\/for\}/is", " } ?>", $template);
$template = preg_replace("/$const_regexp/", "=\\1?>", $template);//note {else} 也符合常量格式,此处要注意先后顺序
$template = preg_replace("/(\\\$[a-zA-Z_]\w+\[)([a-zA-Z_]\w+)\]/i", "\\1'\\2']", $template);
$fp = fopen($this->objfile, 'w');
fwrite($fp, $template);
fclose($fp);
}
function arrayindex($name, $items) {
$items = preg_replace("/\[([a-zA-Z_]\w*)\]/is", "['\\1']", $items);
return "=$name$items?>";
}
function stripvtag($s) {
$vtag_regexp = "\";
return preg_replace("/$vtag_regexp/is", "\\1", str_replace("\\\"", '"', $s));
}
function loopsection($arr, $k, $v, $statement) {
$arr = $this->stripvtag($arr);
$k = $this->stripvtag($k);
$v = $this->stripvtag($v);
$statement = str_replace("\\\"", '"', $statement);
return $k ? " foreach((array)$arr as $k => $v) {?>$statement}?>" : " foreach((array)$arr as $v) {?>$statement } ?>";
}
function __destruct() {
$content = ob_get_contents();
//处理 rewrite
if($this->rewrite) {
$arr=$this->rewrite_rule;
$s=$arr[0];
$e=$arr[1];
$content=preg_replace($s,$e,$content);
}
ob_end_clean();
echo $content;
}
}
$tpl = new template('skin',"default");
$tpl->objdir='tpp';
$tpl->rewrite=true;//开启rewrite 需要服务器支持
$tpl->rewrite_rule=array(array("/index\.php/"),array("index.html")); //rewrite规则
$tpl->assign("indexurl","index.php");
$tpl->assign("str","我是字符串啦啦啦");
$tpl->assign("ec","我是被echo出来的");
$tpl->assign("subhtml","{subtpl ttt}这是用来引入一个模板文件的,这个就是引入ttt.htm");
$tpl->assign("a",array('dasdasd'.'bbbbbbb','cccccccccccccc'));
$tpl->assign("i",1);
$tpl->display("index");
?>


新建 tpl/default/index.html

复制代码 代码如下:






본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

화웨이 GT3 Pro와 GT4의 차이점은 무엇입니까? 화웨이 GT3 Pro와 GT4의 차이점은 무엇입니까? Dec 29, 2023 pm 02:27 PM

많은 사용자들이 스마트 시계를 선택할 때 Huawei 브랜드를 선택하게 됩니다. 그 중 Huawei GT3pro와 GT4가 가장 인기 있는 선택입니다. 두 제품의 차이점을 궁금해하는 사용자가 많습니다. Huawei GT3pro와 GT4의 차이점은 무엇입니까? 1. 외관 GT4: 46mm와 41mm, 재질은 유리 거울 + 스테인레스 스틸 본체 + 고해상도 섬유 후면 쉘입니다. GT3pro: 46.6mm 및 42.9mm, 재질은 사파이어 유리 + 티타늄 본체/세라믹 본체 + 세라믹 백 쉘입니다. 2. 건강한 GT4: 최신 Huawei Truseen5.5+ 알고리즘을 사용하면 결과가 더 정확해집니다. GT3pro: ECG 심전도, 혈관 및 안전성 추가

수정: Windows 11에서 캡처 도구가 작동하지 않음 수정: Windows 11에서 캡처 도구가 작동하지 않음 Aug 24, 2023 am 09:48 AM

Windows 11에서 캡처 도구가 작동하지 않는 이유 문제의 근본 원인을 이해하면 올바른 솔루션을 찾는 데 도움이 될 수 있습니다. 캡처 도구가 제대로 작동하지 않는 주요 이유는 다음과 같습니다. 초점 도우미가 켜져 있습니다. 이렇게 하면 캡처 도구가 열리지 않습니다. 손상된 응용 프로그램: 캡처 도구가 실행 시 충돌하는 경우 응용 프로그램이 손상되었을 수 있습니다. 오래된 그래픽 드라이버: 호환되지 않는 드라이버가 캡처 도구를 방해할 수 있습니다. 다른 응용 프로그램의 간섭: 실행 중인 다른 응용 프로그램이 캡처 도구와 충돌할 수 있습니다. 인증서가 만료되었습니다. 업그레이드 프로세스 중 오류로 인해 이 문제가 발생할 수 있습니다. 이 문제는 대부분의 사용자에게 적합하며 특별한 기술 지식이 필요하지 않습니다. 1. Windows 및 Microsoft Store 앱 업데이트

iPhone에서 App Store 오류에 연결할 수 없는 문제를 해결하는 방법 iPhone에서 App Store 오류에 연결할 수 없는 문제를 해결하는 방법 Jul 29, 2023 am 08:22 AM

1부: 초기 문제 해결 단계 Apple 시스템 상태 확인: 복잡한 솔루션을 살펴보기 전에 기본 사항부터 시작해 보겠습니다. 문제는 귀하의 기기에 있는 것이 아닐 수도 있습니다. Apple 서버가 다운되었을 수도 있습니다. Apple의 시스템 상태 페이지를 방문하여 AppStore가 제대로 작동하는지 확인하세요. 문제가 있는 경우 Apple이 문제를 해결하기를 기다리는 것뿐입니다. 인터넷 연결 확인: "AppStore에 연결할 수 없음" 문제는 때때로 연결 불량으로 인해 발생할 수 있으므로 인터넷 연결이 안정적인지 확인하십시오. Wi-Fi와 모바일 데이터 간을 전환하거나 네트워크 설정을 재설정해 보세요(일반 > 재설정 > 네트워크 설정 재설정 > 설정). iOS 버전을 업데이트하세요.

Jul 25, 2023 pm 01:18 PM

MySQL은 데이터를 처리하고 운영하는 다양한 기능을 제공하는 일반적으로 사용되는 관계형 데이터베이스 관리 시스템입니다. 그 중 REPLACE 함수는 문자열의 지정된 부분을 바꾸는 데 사용됩니다. 이 기사에서는 MySQL에서 문자열 교체를 위해 REPLACE 함수를 사용하는 방법을 소개하고 코드 예제를 통해 사용법을 보여줍니다. 먼저 REPLACE 함수의 구문인 REPLACE(str,search_str,replace_str)를 살펴보겠습니다.

Python의 문자열 검색 및 바꾸기 기술은 무엇입니까? Python의 문자열 검색 및 바꾸기 기술은 무엇입니까? Oct 20, 2023 am 11:42 AM

Python의 문자열 검색 및 바꾸기 기술은 무엇입니까? (특정 코드 예) Python에서 문자열은 일반적인 데이터 유형이므로 일상적인 프로그래밍에서 문자열 검색 및 바꾸기 작업을 자주 접하게 됩니다. 이 기사에서는 특정 코드 예제와 함께 몇 가지 일반적인 문자열 검색 및 대체 기술을 소개합니다. 문자열에서 특정 하위 문자열을 찾으려면 문자열의 find() 메서드나 index() 메서드를 사용할 수 있습니다. find() 메소드는 문자열에서 부분 문자열이 처음 나타나는 인덱스를 반환합니다.

Golang 및 템플릿 패키지: 개인화된 사용자 인터페이스 만들기 Golang 및 템플릿 패키지: 개인화된 사용자 인터페이스 만들기 Jul 18, 2023 am 10:27 AM

Golang 및 템플릿 패키지: 개인화된 사용자 인터페이스 만들기 현대 소프트웨어 개발에서 사용자 인터페이스는 사용자가 소프트웨어와 상호 작용하는 가장 직접적인 방법인 경우가 많습니다. 사용하기 쉽고 아름다운 사용자 인터페이스를 제공하기 위해 개발자는 사용자 인터페이스를 만들고 사용자 정의할 수 있는 유연한 도구가 필요합니다. Golang에서 개발자는 템플릿 패키지를 사용하여 이 목표를 달성할 수 있습니다. 이 기사에서는 Golang 및 템플릿 패키지의 기본 사용법을 소개하고 코드 예제를 통해 개인화된 사용자 인터페이스를 만드는 방법을 보여줍니다.

Golang의 템플릿 패키지를 통한 데이터 시각화 Golang의 템플릿 패키지를 통한 데이터 시각화 Jul 17, 2023 am 09:01 AM

Golang의 템플릿 패키지를 통한 데이터 시각화 빅데이터 시대의 도래와 함께 데이터 시각화는 정보 처리 및 분석의 중요한 수단 중 하나가 되었습니다. 데이터 시각화는 데이터를 간결하고 직관적인 방식으로 제시하여 사람들이 데이터를 더 잘 이해하고 분석하도록 돕습니다. Golang에서는 템플릿 패키지를 사용하여 데이터 시각화 기능을 구현할 수 있습니다. 이 기사에서는 Golang의 템플릿 패키지를 사용하여 데이터 시각화를 구현하고 코드 예제를 제공하는 방법을 소개합니다. 골랑템

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

See all articles