【发布时间】:2012-09-27 14:31:49
【问题描述】:
我正在用 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 行]:语法错误:无效属性名称:'$names'(Smarty_Compiler.class.php,第 1550 行)在 C:\xampp\php\Smarty\libs \Smarty.class.php 在第 1094 行。
同样的情况也发生在 $users 身上。因为我知道这些值正在传递,因为它正在工作,所以我无法理解发生了什么。
提前谢谢。
编辑:我从 smarty 网站上拿了这个例子。
【问题讨论】:
-
您使用的是 Smarty3 引入的语法,但实际上是在运行 Smarty2。要么升级到 Smarty3(3.1.12 是当前版本),要么将你的 foreach 更改为
{foreach from=$users item=user}