Php 如何编写循环数据库记录的Smarty块插件

Php 如何编写循环数据库记录的Smarty块插件,php,plugins,smarty,Php,Plugins,Smarty,假设数据库中有一个Category(parent)和Product(child)表,比如说,我想创建Smarty Block插件,以支持类似以下内容的模板片段: {products category="Some Category"} <h1>{products_name}</h2> <p>{products_description}</p> {/products} {products category=“Some category

假设数据库中有一个Category(parent)和Product(child)表,比如说,我想创建Smarty Block插件,以支持类似以下内容的模板片段:

{products category="Some Category"}
    <h1>{products_name}</h2>
    <p>{products_description}</p>
{/products}
{products category=“Some category”}
{产品名称}
{产品描述}

{/products}
我相信这样的插件将有助于避免重复读取数据库的代码块,并在我的控制器中对结果进行smarty赋值

我知道如何把它写成smarty函数。但我正在寻找一个块版本,以使模板设计师能够灵活地以任何他想要的方式设计各个列的样式。我是一名长期的Perl程序员,对Smarty还不熟悉。例如,Perl用户会在Movable Type模板系统中识别出类似的内容,我想知道smarty版本是否可行


这样的事情在Smarty中可能吗?从smarty插件内部调用DB是件好事吗

我的建议是将配置数组($conf)与SQL查询模板一起使用,以便在插件内部进行简单修改。 当然,在Smarty插件中进行DB调用不是一件好事。相反,您可以将结果加载到$conf数组中,在PHP脚本中进行DB调用,然后根据需要在插件中卸载

这是Smarty插件:

<?php
function smarty_block_products($params, $content, &$smarty, &$repeat)
{
    global $conf;

    $category = $params['category'];
    $md5 = md5($category);
    if (empty($content))
    {
        if (empty($category))
        {
            $smarty->trigger_error("products: missing 'category' parameter"); 
        }
        $sql = str_replace('{$category}', $category, $conf['get-products-sql-template']);
        $query = mysql_query($sql);

        $result = array();
        while ($row = mysql_fetch_assoc($query))
        {
            $result[] = $row;
        }
        if (count($result) == 0)
        {
            $result = false;
        }
        $GLOBALS['__SMARTY_PRODUCTS'][$md5] = $result;
    }
    if (is_array($GLOBALS['__SMARTY_PRODUCTS'][$md5]))
    {
        $field = "product";
        if (isset($params['item']))
        {
            $field = $params['item'];
        }

        $product = array_shift($GLOBALS['__SMARTY_PRODUCTS'][$md5]);            

        $smarty->assign($field, $product);

        if (count($GLOBALS['__SMARTY_PRODUCTS'][$md5]) == 0)
        {
            $GLOBALS['__SMARTY_PRODUCTS'][$md5] = false;
        }
        $repeat = true;
    } else {
        $repeat = false;
    }
    echo $content;
}
?>

Smarty模板:

{products category="Some Category" item=product}
    <h1>{$product.name}</h2>
    <p>{$product.description}</p>
{/products}
{products category=“Some category”item=product}
{$product.name}
{$product.description}

{/products}
而PHP:

<?php
require 'Smarty/Smarty.class.php';

$smarty = new Smarty;

$conf['get-products-sql-template'] = 'SELECT product.* FROM product INNER JOIN category ON category.id = product.category_id WHERE category.title = \'{$category}\'';

$smarty->display('test.tpl');
?>