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

Slim Framework v3中PHP向模板传递数据问题求助

解决Slim Framework v3中PHP数据传递到模板的问题

嘿,我看你在Slim 3里把PHP数据传到模板时遇到了麻烦,结合你给出的代码片段,我来帮你搞定这个问题~

首先,咱们先揪出核心问题:你目前只把$args数组传给了模板,但从数据库获取到的玩家数据$row并没有被包含进去。Slim 3的模板渲染器需要你把所有要在模板中使用的数据都放到一个数组里,一起传递给render方法。

具体解决步骤:

  • 合并要传递的所有数据:把URL参数$args和数据库返回的$row数据合并成一个新的数组,这样模板就能同时拿到玩家ID和详细信息了。
  • 修改渲染代码:用合并后的数组替代原来的$args传给模板。
  • 模板中调用数据:在phtml模板里通过对应的键名来访问数据。

修正后的完整代码示例:

$app->get('/user/{playerid}', function (Request $request, Response $response, array $args) {
    $playerid = $args['playerid'];
    $this->logger->info("Someone requested to see the score of the following player: [".$playerid."]");
    $db = Database::Instance();
    $row = $db->getPlayer($playerid);
    
    if ($row === false) {
        return $this->renderer->render($response, 'dataNotFound.phtml', $args);
    }
    
    // 合并URL参数和玩家数据,方便模板调用
    $templateData = array_merge($args, [
        'playerData' => $row
    ]);
    
    // 把合并后的数组传给模板
    return $this->renderer->render($response, 'playerScore.phtml', $templateData);
});

模板中的使用示例(比如playerScore.phtml):

<div class="player-info">
    <h2>玩家ID:<?= $playerid ?></h2>
    <p>当前得分:<?= $playerData['score'] ?></p>
    <p>玩家昵称:<?= $playerData['nickname'] ?></p>
</div>

额外注意点:

  • 如果你的getPlayer方法返回的是对象而不是关联数组,记得把它转成数组再传递,比如'playerData' => (array)$row。
  • 模板里的变量名要和你传递的数组键名完全一致,不然会出现变量未定义的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:15:46