编译器函数 {/programmers/plugins/plugins-compiler-functions/}
编译器函数仅在模板编译期间被调用。它们对于将 PHP 代码或时间敏感的静态内容注入到模板中非常有用。如果同一名称下既有编译器函数又有自定义函数注册,那么编译器函数优先。
mixed smarty_compiler_name(array $params, object $smarty)
编译器函数接收两个参数:包含预编译字符串的属性值的参数数组和 Smarty 对象。它应该返回要注入到编译模板中的代码,包括周围的 PHP 标签。
以下是一个示例,该函数在编译时输出包含源文件名和编译时间的头信息:
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: compiler.tplheader.php
* Type: compiler
* Name: tplheader
* Purpose: Output header containing the source file name and
* the time it was compiled.
* -------------------------------------------------------------
*/
function smarty_compiler_tplheader($params, Smarty $smarty)
{
return "<?php\necho '" . $smarty->_current_file . " compiled at " . date('Y-m-d H:M'). "';\n?>";
}
?>
此函数可以从模板中调用,如下所示:
{* 这个函数只在编译时执行 *}
{tplheader}
在编译模板中生成的 PHP 代码可能如下:
<?php
echo 'index.tpl compiled at 2002-02-20 20:02';
?>