0

Smarty 版本 2,如果我捕获一个静态字符串:

{capture name=test}
 a huge page or string can go here
 {/capture}

我可以简单地使用 {$smarty.capture.test} 在当前模板或子模板中转储我捕获的字符串没问题

如果我尝试捕获“{foreach}”循环,例如:

 {capture name=test}
  {foreach item=Row from=$DataGrid.Rows name=RowsGrid}
    ,['{$Row.DataCells.project_name.Data}', {$Row.DataCells.approved_budget.Data}]
{/foreach}
 {/capture}

我可以在当前模板中轻松使用它,例如:

   {$smarty.capture.test}

并将正确的数据显示为字符串。但是,当我尝试在子模板中使用它时:

 {include file='/full/path/child.tpl'}
 {$smarty.capture.test}

这将导致空捕获的数据,如:

  ,['', ] ,['', ] ,['', ] 

如果我使用 {$smarty.capture.test|var_dump} 它显示为“字符串(86)”我在这里错过了什么?

4

2 回答 2

0

我假设在您的最后一个样本中child.tpl填充了测试变量,然后您尝试在包含模板中使用它。鉴于 Smarty 如何处理范围,空输出是完全正确的 - 范围仅向下继承。父级无法访问其子级设置的变量。

显然,直接在过滤器中使用变量会绕过范围检查,这肯定是实现中的一个错误。话又说回来,Smarty 2 已经存在多年了,v3 已经存在多年了,而Twig在 HTML5 时代更加实用。

于 2014-09-08T22:16:23.730 回答
0

它对我有用,没有问题:

PHP 文件:

$smarty->assign('data', array(
        array('name' => 'a1'),
        array('name' => 'a2'),
        array('name' => 'a3'),
        array('name' => 'a4'),
        array('name' => 'a5')
    ));
$smarty->display('normal.tpl');

normal.tpl文件:

{include file='child.tpl'}
{$smarty.capture.test}

child.tpl文件:

{capture name=test}
    {foreach item=Row from=$data}
        ,['{$Row.name}']
    {/foreach}
{/capture}

输出如预期:

,['a1'] ,['a2'] ,['a3'] ,['a4'] ,['a5'] 

您应该确保正确分配了变量,如果不是这样,您应该提供更多详细信息。

于 2014-09-16T16:46:47.873 回答