


discuz x2.5 Template class extracted from Kangsheng product discuz
Copy 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 需要服务器支持
$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
复制代码 代码如下:
< ;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)

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre
