smarty核心思想 自制模板引擎
<?php $tit = '今天下雨了,淋了半条街'; function tit($file){ //读文件 $h = file_get_contents($file); $h = str_replace('{$','<?php echo $',$h); $h = str_replace('}',';?>',$h); //新文件名 1.html.php $tmp = $file.'.php'; //写到一个文件里 file_put_contents($tmp,$h); return $tmp; } include(tit('1.html'));
读取1.html然后把{$tit} 替换成php语法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {$tit} </body> </html>
封装成一个类,用面向对象思想来搞
<?php class Mini { public $data = array(); public function tit($file) { //读文件 $h = file_get_contents($file); $h = str_replace('{$', '<?php echo $this->data[\'', $h); $h = str_replace('}', '\'];?>', $h); //新文件名 1.html.php $tmp = $file . '.php'; //写到一个文件里 file_put_contents($tmp, $h); return $tmp; } public function assign($key,$value){ $this->data[$key] = $value; } public function display($file){ $filetemp = $this->tit($file); include($filetemp); //这个时候没有这个变量 //echo $tit; } } $tit = '今天下雨了,淋了半条街'; $mini = new Mini(); $mini->assign('mytit',$tit); $mini->display('1.html');
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {$mytit} </body> </html>