跳转到内容

自定义标签

您可以在 Smarty 语言中添加自己的标签。

运行时标签

通常情况下,您会添加一个运行时标签。添加运行时标签需要您提供一个回调函数,该函数接受两个参数

  • $params:模板中的所有属性作为关联数组。
  • $template:一个 Smarty\Template 对象,表示使用标签的模板。

函数的输出(返回值)将替换为模板中标签的位置。

如果该函数需要将一些变量分配给模板或使用一些其他由 Smarty 提供的功能,它可以使用提供的 $template 对象来执行此操作。

<?php

function smarty_tag_eightball($params, \Smarty\Template $template): string {
    $answers = [
        'Yes',
        'No',
        'No way',
        'Outlook not so good',
        'Ask again soon',
        'Maybe in your reality'
    ];

    $result = array_rand($answers);
    return $answers[$result];
}

$smarty->registerPlugin(Smarty\Smarty::PLUGIN_FUNCTION, 'eightball', 'smarty_tag_eightball');

现在可以在模板中使用它

Question: Will we ever have time travel?
Answer: {eightball}.

编译器标签

编译器标签只在编译模板期间调用。

它们对于将 PHP 代码或时间敏感的静态内容注入模板非常有用。如果在相同名称下注册了编译器函数和运行时标签,则编译器函数具有优先权。

编译器函数传递两个参数:包含属性值预编译字符串的 params 数组和 Smarty 对象。它应该返回要注入到已编译模板中的代码,包括周围的 PHP 标记。

示例

<?php

function smarty_compiler_tplheader($params, Smarty $smarty) {
    return "<?php\necho '" . $smarty->_current_file . " compiled at " . date('Y-m-d H:M'). "';\n?>";
}

$smarty->registerPlugin(Smarty\Smarty::PLUGIN_COMPILER, 'tplheader', 'smarty_compiler_tplheader');

此函数可以从模板中调用为

{* this function gets executed at compile time only *}
{tplheader}

已编译模板中的结果 PHP 代码会类似于

<?php
echo 'index.tpl compiled at 2023-02-20 20:02';