[PHP]View Plaincopy
- <?php
- Class myminismarty{
- //template file storage path
- var $template _dir="./templates/";
- //Compile file, the name format of the compiled file is tentatively: Com_ corresponding tpl.php
- var $complie _dir="./templates_c";
- //Template variable array: Store values for all template variables
- var $tpl _vars=Array ();
- //Here we mainly simulate two methods
- //Parameter 1-template variable parameter 2: value of template variable
- function Assign ($tpl _var,$val =null) {
- if ($tpl _var!=") {
- $this->tpl_vars[$tpl _var]=$var;
- }
- }
- //write display here
- //Parameter 1-template filename to display
- function Display ($tpl _file) {
- path to//template file
- $tpl _file_path=$this->template_dir.$tpl _file;
- //Naming and path of compiled files
- $complie _file_path=$this->complie_dir."Com_". $tpl _file. ". php";
- //Determine if the current template file exists
- if (! File_exists ($tpl _file_path)) {
- //returns False if the current template file does not exist
- return false;
- }
- ///See if there are any compiled files, if there is no compiled file, or if the template file is modified more than the build time of the compiled file, you need to recompile
- if (! File_exists ($comlie _file_path) | | filemtime ($tpl _file_path) >filemtime ($complie _file_path)) {
- //Get the contents of a template file
- $tpl _file_content=file_get_contents ($tpl _file_path);
- //Here Our core is how to convert TPL to PHP file
- $pattern =Array (
- //1.\{-Escape {Opening parenthesis 2.\s*-represents one or more spaces 3.\$-escape $ symbol 4.\}-escape} closing parenthesis
- '/\{\s*\$ ([a-za-z][a-za-z0-9]*) \s*\}/i '
- );
- $replace =Array (
- ' <?php echo $this->tpl_vars["${1}"]?> '
- );
- //replace similar {$title} with <?php echo $this->tpl_vars["title"]?, return the replaced string
- $new _str=preg_replace ($pattern,$replace,$tpl _file_content);
- //Compile file generation: Writes the contents of the regular replacement template file to the compiled file
- file_put_contents ($complie _file_path,$new _str);
- }
- //If there is a compilation file and the template file is not changed, the compilation file is introduced directly
- include $complie _file_path;
- }
- }
- ?>
Note: Objects can also be used as template variables
Case:
PHP Files:
$smarty =new smarty ();
$var 1 = "simple string";
$var 2=new object name ();
$var 3=array (Table of contents:);
$smarty->assign ("Var1", $var 1);
$smarty->assign ("Var2", $var 2);
$smarty->assign ("Var3", $var 3);
Template files:
Remove the Var1 value: {$var 1}<br/>
Remove the Var2 value: {$var 2-> property or method}
Remove Var3 value: {$var 3[subscript]}
"Smarty Project source Code" simulation of Smarty template file parsing process