仿thinkphp模板类

作者:root 时间:24-06-05 阅读数:402人阅读
class SimpleTemplate {
    private $templateDir;
    private $data = array();
 
    public function __construct($templateDir) {
        $this->templateDir = $templateDir;
    }
 
    public function assign($key, $value) {
        $this->data[$key] = $value;
    }
 
    public function display($templateName) {
        $templatePath = $this->templateDir . '/' . $templateName;
        if (file_exists($templatePath)) {
            extract($this->data); // 将变量导入到当前符号表
            include $templatePath;
        } else {
            throw new Exception("Template does not exist: $templatePath");
        }
    }
}
 
// 使用示例
$templateDir = 'views';
$template = new SimpleTemplate($templateDir);
$template->assign('name', 'World');
$template->display('hello.php'); // 假设views目录下有hello.php模板文件


本文链接:http://17xinrui.com/?id=47 

分享到: