You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WHMCS中PHP向TPL模板传递数组并循环展示的问题

解决WHMCS自定义PHP页面传值到模板的问题

核心问题原因

WHMCS基于Smarty模板引擎运行,不能直接通过普通PHP变量传递数据,必须通过WHMCS内置的$smarty对象的assign()方法绑定数据到模板变量,同时要确保模板文件放置在正确目录,且PHP文件完成WHMCS环境初始化。

步骤1:正确编写domainList.php

确保PHP文件初始化WHMCS核心环境,调用API并将数据绑定到模板变量:

<?php
// 初始化WHMCS核心环境
require_once __DIR__ . '/init.php';

// API请求参数(推荐用API密钥认证,更安全)
$apiParams = [
    'action' => 'GetTLDPricing',
    'identifier' => 'YOUR_API_IDENTIFIER', // 替换为你的API标识符
    'secret' => 'YOUR_API_SECRET', // 替换为你的API密钥
    'responsetype' => 'json'
];

// 发送API请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GLOBALS['whmcsUrl'] . '/includes/api.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiParams));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

// 解析API响应
$tldData = json_decode($response, true);

// 绑定数据到模板变量
if ($tldData['result'] === 'success') {
    $smarty->assign('tldPricing', $tldData['pricing']);
} else {
    $smarty->assign('apiError', $tldData['message']);
}

// 渲染指定模板
echo $smarty->fetch('domainList.tpl');
?>

步骤2:放置并编写domainList.tpl模板

将模板文件放在当前启用的主题目录下(比如默认主题路径为/templates/six/),内容如下:

<div class="container mt-4">
    <h2>TLD价格列表</h2>

    {if $apiError}
        <div class="alert alert-danger">{$apiError}</div>
    {else}
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>TLD后缀</th>
                    <th>1年注册价</th>
                    <th>1年续费价</th>
                    <th>1年转入价</th>
                </tr>
            </thead>
            <tbody>
                {foreach from=$tldPricing item=prices key=tld}
                    <tr>
                        <td>.{$tld}</td>
                        <td>{$prices.register.1}</td>
                        <td>{$prices.renew.1}</td>
                        <td>{$prices.transfer.1}</td>
                    </tr>
                {/foreach}
            </tbody>
        </table>
    {/if}
</div>

关键注意事项

  • API权限配置:在WHMCS后台「设置 > API凭据」中,确保你的API密钥拥有GetTLDPricing接口的访问权限。
  • 模板路径验证:模板文件必须放在当前启用主题的目录下,否则Smarty无法读取到模板。
  • 认证方式选择:优先使用API密钥(identifier+secret),避免使用用户名+MD5密码的不安全认证方式。
  • 环境初始化:必须引入init.php,否则无法调用WHMCS的$smarty对象和核心配置。

内容的提问来源于stack exchange,提问作者veolio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 03:23:25