简体   繁体   English

如何在Smarty模板中放入类似内容?

[英]How can I put something like this in a Smarty template?

I am trying to convert a pre-existing site that had html and php intermingled into a Smarty template based site. 我正在尝试将html和php混合在一起的现有站点转换为基于Smarty模板的站点。 I never used Smarty before so this is proving very difficult for me. 我以前从未使用过Smarty,因此这对我来说很难。 I get that you can assign a variable like so: 我知道您可以像这样分配一个变量:

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

and use it in the tpl file like so: 并在tpl文件中使用它,如下所示:

{$number_of_items_in_cart}

but what about more complex things like this block of code that I had on the old site: 但是像我以前在旧网站上的代码块这样的更复杂的事情呢:

$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');
}

How can I work with this in a Smarty template, since the output is within a while loop? 由于输出在while循环内,我该如何在Smarty模板中使用它?

Instead of echoing this, you can append it in a string variable then pass it to smarty: 您可以将其附加到字符串变量中,然后将其传递给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>";
    }

Now u can pass it to smarty 现在你可以将它传递给聪明的人

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

I hope this is what you are looking for 我希望这是你要找的

You can use the foreach builtin function to iterate over an array containing your query results. 您可以使用foreach内置函数对包含查询结果的数组进行迭代。
You could also use foreachelse to display an alternate message (though in this case you're redirecting). 您也可以使用foreachelse显示替代消息(尽管在这种情况下您正在重定向)。

See example 7.9 in http://www.smarty.net/docsv2/en/language.function.foreach . 请参阅http://www.smarty.net/docsv2/zh/language.function.foreach中的示例7.9。

Edit: there's also a while function if that's what you really want. 编辑:如果那是您真正想要的,还有一个while函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM