【问题标题】:Working with smarty template engine for WHMCS. Need to use php function from external php file in .tpl file使用 WHMCS 的 smarty 模板引擎。需要在 .tpl 文件中使用来自外部 php 文件的 php 函数
【发布时间】:2017-05-31 05:43:35
【问题描述】:

试图在 A.tpl 中获取输出但没有得到任何输出。我想我在 tpl 文件中调用 php 函数做错了。

A.tpl

{myModifier}

B.php

class Geolocation{
    public function sm_loc($params, Smarty_Internal_Template $template)
    {
        return "100.70";
    }
}

$smarty1 = new Smarty();

$smarty1->registerPlugin('modifier', 'myModifier', array('Geolocation', 'sm_loc'));

我已经使用过这段代码。这似乎不起作用。它还破坏了我在 A.tpl 中的现有工作代码发布此使用。

我的需要是从外部 php 文件中获取 A.tpl 中 php 函数的输出。

提前致谢。对不起,我是菜鸟。

【问题讨论】:

    标签: php smarty whmcs smarty3 smarty-plugins


    【解决方案1】:

    要将此修饰符添加到 Smarty 并在模板中使用它,最好使用 WHMCS 挂钩。

    如果你在 '~/includes/hooks/' 目录下创建一个新的 PHP 文件(你可以给它起任何名字 - 在这种情况下,让我们使用 'myhook.php'),WHMCS 将在每​​个请求上自动注入这个钩子.

    为此,您将需要使用ClientAreaPage 挂钩。在您的钩子中,您可以访问全局 $smarty 变量。

    例子:

    function MySmartyModifierHook(array $vars) {
        global $smarty;
    
        // I recommend putting your Geolocation class in a separate PHP file,
        // and using 'include()' here instead.
        class Geolocation{
            public function sm_loc($params, Smarty_Internal_Template $template) {
                return "100.70";
            }
        }
    
        // Register the Smarty plugin
        $smarty->registerPlugin('modifier', 'myModifier', array('Geolocation', 'sm_loc'));
    }
    
    // Assign the hook
    add_hook('ClientAreaPage', 1, 'MySmartyModifierHook');
    

    这应该可以解决问题。如果你想探索其他的钩子,你可以看看 WHMCS 文档中的Hook Index

    每个挂钩文件中的函数名称​​必须是唯一的。

    附带说明,如果您只想在特定页面上运行此挂钩,可以检查传递的 $vars 数组中的 templatefile 键。例如,假设您只希望此挂钩在订单表单的“查看购物车”页面上运行:

    function MySmartyModifierHook(array $vars) {
        global $smarty;
    
        // If the current template is not 'viewcart', then return
        if ($vars['templatefile'] != 'viewcart')
            return;
    
        // ... your code here ...
    }
    

    另外,请注意,使用诸如“ClientAreaPage”钩子之类的钩子,返回一个键和值数组将自动将它们添加为 Smarty 变量。所以如果你的钩子函数以return ['currentTime' => time()];结尾,你可以在Smarty模板中使用{$currentTime}来输出它的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多