在smarty中获取foreach循环的数据

时间:2013-02-07 07:46:10

标签: php sql foreach smarty

我正在尝试将smarty用于新网站,但我有一个问题,即将数据从sql查询分配给smartyt foreach循环。我没有从查询中获取任何数据到我的模板。

在我的class.designs.php中我有这个:

    function listAllDesigns() {
            global $db;

            $row = $db->query("
SELECT ds.*, count(com.comment) AS countcom 
FROM designs ds LEFT JOIN comments com ON com.design_id = ds.id 
WHERE ds.approved = 1 
GROUP BY ds.id 
ORDER BY ds.date_added ASC")->resultset();        

            $smarty = new Smarty;        
            $smarty->assign('designs', $row);

            return;        
        }

和我的index.php

include_once("includes/connect.php"); //Database connection
include_once("includes/config.php"); //Configuration file
include_once("includes/classes/class.designs.php"); //Main design class

require('smarty/libs/Smarty.class.php');

$designs = new Designs();
$designs->listAllDesigns();

$smarty = new Smarty;
$smarty->debugging = true;
$smarty->caching = true;
$smarty->cache_lifetime = 120;

$smarty->assign("charset", $config->charset);
$smarty->assign("pagetitle", $config->pagetitle);
$smarty->display('index.tpl');

并在index.tpl中我有:

{foreach $designs as $r}
  <li>{$r.name}</li>
{foreachelse}
   No results 
{/foreach}

只打印“无结果”,我收到“未定义的索引设计”错误。

1 个答案:

答案 0 :(得分:0)

include_once("includes/connect.php"); //Database connection
include_once("includes/config.php"); //Configuration file
include_once("includes/classes/class.designs.php"); //Main design class

require('smarty/libs/Smarty.class.php');

$designs = new Designs();
$designs->listAllDesigns();

$smarty = new Smarty;
$smarty->debugging = true;
$smarty->caching = true;
$smarty->cache_lifetime = 120;

// TO USE some value ($designs in your case) at your template you must assign it
// 1st is its name and 2nd is the value
$smarty->assign("designs", $designs);

$smarty->assign("charset", $config->charset);
$smarty->assign("pagetitle", $config->pagetitle);
$smarty->display('index.tpl');