You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自研类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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 17:56:35