Skip to content

\$default_template_handler_func {#variable.default.template.handler.func}

这个函数在无法从资源中获取模板时被调用。

注意

默认处理程序目前只对文件资源起作用。当资源本身无法找到时,它不会被触发,此时会抛出一个 SmartyException 异常。

<?php

$smarty = new Smarty();
$smarty->default_template_handler_func = 'my_default_template_handler_func';

/**
 * 默认模板处理程序
 *
 * 当 Smarty 的文件资源无法加载请求的文件时调用
 *
 * @param string   $type     资源类型(例如 "file"、"string"、"eval"、"resource")
 * @param string   $name     资源名称(例如 "foo/bar.tpl")
 * @param string  &$content  模板的内容
 * @param integer &$modified 模板的修改时间
 * @param Smarty   $smarty   Smarty 实例
 * @return string|boolean   文件路径或者如果已填充 $content 和 $modified,则返回布尔值 true,
 *                          如果无法加载默认模板,则返回布尔值 false
 */
function my_default_template_handler_func($type, $name, &$content, &$modified, Smarty $smarty) {
    if (false) {
        // 返回修正后的文件路径
        return "/tmp/some/foobar.tpl";
    } elseif (false) {
        // 直接返回一个模板
        $content = "the template source";
        $modified = time();
        return true;
    } else {
        // 告诉 Smarty 加载失败
        return false;
    }
}

?>

以上是一个示例代码,演示了如何设置 $smarty->default_template_handler_func 并实现自定义的默认模板处理程序。该函数接收资源类型、资源名称、模板内容和修改时间等参数,并根据需要返回修正后的文件路径、填充模板内容和修改时间,或告诉 Smarty 加载失败。