自研类WordPress get_template_part()函数的合理性及优化咨询
自定义模板加载函数的合理性与优化疑问
我偏好WordPress的get_template_part()函数——它本质是加载PHP文件,却无需编写require_once、require、include这类语句,还能将模板内容以变量形式返回。但WordPress该函数的调用嵌套层级过多,我难以理清其实际实现逻辑,于是自行编写了一个简化版函数,却不确定这种实现是否合理,担心在大型系统中批量加载不同PHP模板时会产生较大性能负担。希望有人能帮忙检查该函数是否适用于大型系统;若不合适,烦请告知WordPress的实现方式,或协助优化该函数以规避潜在问题。此外我还编写了另一个函数,但并不满意——它仅能解析变量,无法执行PHP代码。
第一个自定义函数(加载PHP模板并返回内容)
function get_template_part( $template ) { $path = dirname(__DIR__) . DIRECTORY_SEPARATOR .'admin'. DIRECTORY_SEPARATOR .'templates'. DIRECTORY_SEPARATOR; if ( file_exists( $path . $template .'.php' ) ) { ob_start(); require_once $path . $template .'.php'; return ob_get_clean(); } else return "<strong>Template Missing:</strong> ".$template.".php"; }
第二个自定义函数(仅解析变量,不执行PHP)
function template($fname) { $tfile = TEMP_DIR."/$fname.tpl"; if(!file_exists($tfile)) return "<br /><b>warning</b> : missing template - $fname<br />"; $data = file_get_contents($tfile); $data = str_replace("\"","\\\"",$data); return $data; } function eval_template($tpl) { $tpl_data = template($tpl); $arr = array(); if( preg_match_all('/\$\w+/', $tpl_data, $matches) ) { $arr = array_unique($matches[0]); foreach($arr as $v) { $v = str_replace('$','',$v); global ${"$v"}; } } }
内容的提问来源于stack exchange,提问作者Themer
相关产品推荐
相关产品推荐

