


Template class extracted from Kangsheng products (discuz)_PHP tutorial
/*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
@ Good things are shared with everyone. 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 rule
$tpl->assign("indexurl","index.php") ;
$tpl->assign("str","I am a 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 to enable 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;//Compile 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 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 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];
$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
1 .String assignment:
{$str}
2. Array assignment:
{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 can also echo
{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 know
New tpl/default/ttt.html
New tpp directory is ok

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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











This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
