我正在用 Smarty 做一些实验,但我在使用 foreach 循环时遇到了问题,它不起作用,我不明白为什么。这是我的代码:
默认.tpl
<select name="user">
{html_options values=$id output=$names selected="5"}
</select>
<table>
{foreach $names as $name}
{strip}
<tr bgcolor="{cycle values='#eeeeee,#dddddd'}">
<td>{$name}</td>
</tr>
{/strip}
{/foreach}
</table>
<table>
{foreach $users as $user}
{strip}
<tr bgcolor="{cycle values='#aaaaaa,#bbbbbb'}">
<td>{$user.name}</td>
<td>{$user.phone}</td>
</tr>
{/strip}
{/foreach}
</table>
和 default.php
<?php
include('Smarty.class.php');
//create object
$smarty = new Smarty;
$smarty->template_dir = 'C:\xampp\htdocs\smarty\templates';
$smarty->config_dir = 'C:\xampp\htdocs\smarty\config';
$smarty->cache_dir = 'C:\xampp\php\smarty\cache';
$smarty->compile_dir = 'C:\xampp\php\smarty\templates_c';
$smarty->assign('names', array('Bob', 'Jimmy', 'Freddy', 'Walter', 'Jerry'));
$smarty->assign('users', array(
array('name' => 'bob', 'phone' => '555-3425'),
array('name' => 'jim', 'phone' => '555-4364'),
array('name' => 'joe', 'phone' => '555-3422'),
array('name' => 'jerry', 'phone' => '555-4973'),
array('name' => 'fred', 'phone' => '555-3235')
));
//display information
$smarty->display('default.tpl');
?>
测试时出现以下错误:
致命错误:Smarty 错误:[在 default.tpl 第 16 行]:语法错误:无效属性名称:C:\xampp\php\Smarty\libs\Smarty 中的“$names”(Smarty_Compiler.class.php,第 1550 行)。第 1094 行的 class.php。
$users 也是如此。因为我知道这些值正在传递,因为它正在工作,所以我无法理解发生了什么。
提前谢谢。
编辑:我从 smarty 网站上拿了这个例子。