


discuz x2.5 Template class extracted from Kangsheng product discuz
Jul 29, 2016 am 08:45 AMCopy the code The code is as follows:
/*template.class.php
@ Kangsheng Weibo Template Extraction Class I think this template is easy to use. Take some time to make it independently.by Lei Rijin
@ took a look at the ctt template. Is it similar to the phpcms template? ? ^_^ Hehe! ! !
@ Weibo http://weibo.com/lrjxgl
@ Everyone shares the good stuff. If you have any questions about the extraction, please ask
@ The default template file is .htm
$tpl = new template('skin',"default" );
$tpl->objdir='tpp';
$tpl->rewrite=true;//Enabling rewrite requires server support
$tpl->rewrite_rule=array(array("/index.php/" ),array("index.html")); //rewrite rules
$tpl->assign("indexurl","index.php");
$tpl->assign("str","I am String la la la");
$tpl->assign("ec","I was echoed out");
$tpl->assign("subhtml","{subtpl ttt}This is used To introduce a template file, this is to introduce ttt.htm");
$tpl->assign("a",array('dasdasd'.'bbbbbbb','cccccccccccccc'));
$tpl-> assign("i",1);
$tpl->display("index");
*/
if(!defined("CHARSET")) define("CHARSET","gb2312");//character Encoding
if(!defined("DIR_TPL")) define("DIR_TPL","tpl");//Default template directory
if(!defined("DIR_DATA")) define("DIR_DATA","data"); //Default data directory
if(!defined("DEBUG")) define("DEBUG",0);//Default running mode
class template {
//note var
public $rewrite=false;//Whether it is enabled Pseudo-static rewrite
public $rewrite_rule=array(); //Set pseudo-static rules
public $defaulttpldir;//Default template
public $tpldir;//Template directory
public $objdir;//Compilation cache directory
public $ tplfile;//Template file
public $objfile;//Compiled file
public $tplid=1;//Template number
public $currdir='default';//Current style directory
public $vars=array();/ /note variable table
public $removeblanks=false;//remove spaces
public $stdout='display';//output type
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 public
function assign($k, $v) {
$this-> vars[$k] = $v;
}
//note public
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 default directory
if(@filemtime($this- >tplfile) === FALSE) {
$this->tplfile = $this->defaulttpldir.'/'.($subdir ? $subdir.'/' : '').$file.'.htm ';
}
//note Determine whether the comparison is expired
if(!file_exists($this->objfile) || DEBUG && @filemtime($this->objfile) < filemtime($this->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 = "=(@?\$[a -zA-Z_]w*(?:[[w."'[]$]+])*)?>";
$const_regexp = "{([w]+)}";
$template = file_get_contents ($this->tplfile);
for($i = 1; $i <= 3; $i++) {
if(strpos($template, '{subtpl') !== FALSE) {
if( DEBUG == 2) {
$template = str_replace('{subtpl ', '{tpl ', $template);
} else {
$template = preg_replace("/[nrt]*{subtpls+([a-z0- 9_:/]+)}[nrt]*/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("/=(@?\$[a-zA-Z_]w*)(([[\$[]w]+])+)?>/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("/[nrt]*{echos+(.+?)}[nrt]*/ies", "$this->stripvtag(' echo \1; ?>','')", $template);
$template = preg_replace("/{for (.*?)}/ies", "$this->stripvtag(' for(\1) {?>')", $template);
$template = preg_replace("/{elseifs+(.+?)}/ies", "$this->stripvtag(' } elseif(\1) { ?>')", $template);
for($i=0; $i<2; $i++) {
$template = preg_replace("/{loops+$vtag_regexps+$vtag_regexps+$vtag_regexp}(.+?){/loop}/ies", "$this->loopsection('\1', '\2', '\3', '\4')", $template);
$template = preg_replace("/{loops+$vtag_regexps+$vtag_regexp}(.+?){/loop}/ies", "$this->loopsection('\1', '', '\2', '\3')", $template);
}
$template = preg_replace("/{ifs+(.+?)}/ies", "$this->stripvtag(' if(\1) { ?>')", $template);
$template = preg_replace("/{tpls+(w+?)}/is", " include $this->getObj("\1");?>", $template);
$template = preg_replace("/{tpls+(.+?)}/ise", "$this->stripvtag(' include $this->getObj("\1"); ?>')", $template);
$template = preg_replace("/{tmptpls+(w+?)}/is", " include $this->getObj("\1", $this->objdir);?>", $template);
$template = preg_replace("/{tmptpls+(.+?)}/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 = "=(@?\$[a-zA-Z_]w*(?:[[w."'[]$]+])*)?>";
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];
$c
}
ob_end_clean();
echo $content;
}
}
$tpl = new template('skin',"default");
$tpl->objdir='tpp';
$tpl->rewrite=true;//開啟rewrite 需要服務(wù)器支持
$tpl->rewrite_rule=array(array("/index.php/"),array("index.html")); //rewrite規(guī)則
$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
復(fù)制代碼 代碼如下:
< ;html xmlns="http://www.w3.org/1999/xhtml">
1. String assignment:
{$str}
2. Array assignment:< br />
{loop $a $v}{$v},{/loop}
or
{loop $a $key $val }{$val},{/loop}
3 .{$subhtml}
{subtpl ttt}
4. Originally I was {$indexurl } and now I have been turned into index.php
5.I I can also echo it
{echo $ec}
6. In fact, I can also add, subtract, multiply and divide 6*7*8
{echo 6*7*8;}
7. These are the commonly used ones, what else don’t you understand
Create new tpl/default/ttt.html
Create a new tpp directory OK
The above introduces the template class of discuz x2.5 extracted from the Kangsheng product discuz, including the content of discuz x2.5. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

ToversionaPHP-basedAPIeffectively,useURL-basedversioningforclarityandeaseofrouting,separateversionedcodetoavoidconflicts,deprecateoldversionswithclearcommunication,andconsidercustomheadersonlywhennecessary.StartbyplacingtheversionintheURL(e.g.,/api/v

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

Proceduralandobject-orientedprogramming(OOP)inPHPdiffersignificantlyinstructure,reusability,anddatahandling.1.Proceduralprogrammingusesfunctionsorganizedsequentially,suitableforsmallscripts.2.OOPorganizescodeintoclassesandobjects,modelingreal-worlden

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.
