首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Smarty3中,从插件函数中调用由{ function }标记定义的模板函数

在Smarty3中,从插件函数中调用由{ function }标记定义的模板函数
EN

Stack Overflow用户
提问于 2012-02-05 19:00:16
回答 3查看 728关注 0票数 1

Smarty {call}内置函数能够调用由{ function }标记定义的模板函数。现在,我需要调用一个模板函数,但是在插件函数中,因为我只知道插件中的函数名。

插件功能:

代码语言:javascript
复制
<?php

$smarty->registerPlugin('function', 'form_label', 'renderFormLabel');

function renderFormLabel($form, \Smarty_Internal_Template $template) {

    // find out which function to call based on the available ones
    $function = lookupTemplateFunction($template);

    $args = $form->getVariables();

    // How to call the Smarty template function with the given $args?
    // $html = $template->smarty->???($args); 

    //return $html;
}

模板:

代码语言:javascript
复制
<form action="submit.php" method="post">
    {form_label}
    ....
</form>

这是一种在https://github.com/noiselabs/SmartyBundle中支持https://github.com/noiselabs/SmartyBundle的努力。每个表单片段都由一个Smarty函数表示。若要自定义窗体呈现方式的任何部分,用户只需覆盖适当的函数即可。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-02-05 21:48:39

我应该在我的第一个回答中更具体一些。renderFormLabel的代码应该如下所示:

代码语言:javascript
复制
function renderFormLabel($form, \Smarty_Internal_Template $template) {

    // find out which function to call based on the available ones
    $function = lookupTemplateFunction($template);

    if ($template->caching) {
        Smarty_Internal_Function_Call_Handler::call ('test',$template,$form,$template->properties['nocache_hash'],false);
    } else {
        smarty_template_function_test($template,$form);
    }
}

在这种情况下,由renderFormLabel数组传递给$form插件的属性(参数)将被视为模板函数中的本地模板变量。

票数 2
EN

Stack Overflow用户

发布于 2012-02-05 19:47:15

可以从插件内部调用模板函数。但是我们最初确实为这个选项做了计划,所以如果缓存是否启用,目前API是不同的。这种情况在今后的发行版中也可能发生变化。

假设您希望在插件中执行类似于{调用name=test world='hallo'}的操作:

代码语言:javascript
复制
if ($template->caching) {
   Smarty_Internal_Function_Call_Handler::call ('test',$template,array('world'=>'hallo'),$template->properties['nocache_hash'],false);
} else {
   smarty_template_function_test($template,array('world'=>'hallo'));
}

注意,模板函数是在调用插件的模板上下文中调用的。调用模板中已知的所有模板变量都在模板函数中自动知道。

模板函数不返回HTML输出,而是直接将其放入输出缓冲区。

票数 3
EN

Stack Overflow用户

发布于 2012-02-05 20:01:43

就我所能理解的您的需要而言,您希望使用已知的args调用一个命名的方法。

为什么不使用这样的call_user_func_array调用:

代码语言:javascript
复制
call_user_func_array(array($template->smarty, $function), $args);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9152047

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档