【问题标题】:How can I put something like this in a Smarty template?我怎样才能把这样的东西放在 Smarty 模板中?
【发布时间】:2011-08-20 22:48:05
【问题描述】:

我正在尝试将混合了 html 和 php 的现有网站转换为基于 Smarty 模板的网站。我以前从未使用过 Smarty,所​​以这对我来说非常困难。我知道你可以像这样分配一个变量:

$smarty->assign('number_of_items_in_cart', $number_of_items_in_cart);

并像这样在 tpl 文件中使用它:

{$number_of_items_in_cart}

但是像我在旧网站上的这段代码这样更复杂的东西呢:

$query = mysql_query(" SELECT * FROM products WHERE id = '$pid' ");

if (mysql_num_rows($query) == 1) {

    while ($row = mysql_fetch_array($query)) {
        extract($row);
        echo "<h2>$name</h2>";
        echo "<img src='images/product_images/$image' alt='' width='100' />";
        echo $description;
        echo '<p>'.money($price).'</p>';
        echo "<input type='text' value='1' class='qty-$id' />";
        echo "<a href='javascript:void(0)' onClick=\"add_cart('$id')\">Add to Cart</a>";
    }

} else {
    redirect('404.php');
}

由于输出在 while 循环中,我如何在 Smarty 模板中使用它?

【问题讨论】:

    标签: php smarty templating


    【解决方案1】:

    您可以将其附加到字符串变量中,然后将其传递给 smarty,而不是回显它:

    $string = "";
    while ($row = mysql_fetch_array($query)) {
            extract($row);
            $string .= "<h2>$name</h2>";
            $string .=  "<img src='images/product_images/$image' alt='' width='100' />";
            $string .=  $description;
            $string .=  '<p>'.money($price).'</p>';
            $string .=  "<input type='text' value='1' class='qty-$id' />";
            $string .=  "<a href='javascript:void(0)' onClick=\"add_cart('$id')\">Add to Cart</a>";
        }
    

    现在你可以将它传递给 smarty

    $smarty->assign('place_holder', $string);
    

    我希望这就是你要找的东西

    【讨论】:

    • 这行得通,但总的来说我认为模板是愚蠢的。我只是为了工作而学习它,也许当我了解更多时我的想法会改变,但第一印象似乎没有必要且耗时。
    • 我理解你,但是当你想分离你的代码,而不是混合 html 和 php 时,这是有道理的。例如,假设你想让一个设计师和一个开发者一起工作,设计师会被所有的代码压得喘不过气来,很难做出最细微的改变。但是使用模板,它可以很容易地将 php 和 html 分开,因此不必知道另一个是如何工作的
    【解决方案2】:

    您可以使用 foreach 内置函数来遍历包含查询结果的数组。
    您还可以使用foreachelse 来显示替代消息(尽管在这种情况下您正在重定向)。

    参见http://www.smarty.net/docsv2/en/language.function.foreach 中的示例 7.9。

    编辑:还有一个 while 函数,如果那是你真正想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-12
      • 2012-02-09
      • 2021-02-02
      • 2017-05-25
      • 2020-12-19
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      相关资源
      最近更新 更多