gpt4 book ai didi

php - 在 smarty 中处理递归的最佳方法是什么?

转载 作者:可可西里 更新时间:2023-11-01 12:44:50 25 4
gpt4 key购买 nike

我发现了几种在 Smarty 中处理递归的方法,主要是基于将模板包含在自身中,这似乎是一种荒谬的资源浪费。我在 Smarty 的 Messju 找到了一个解决方案,它似乎是正确的 - 但它不受支持并且在最新版本的 smarty 中失败:(

对于提问的人:我希望 smarty 打印出的是一个由条目数组定义的讨论线程。如果一个条目有一个或多个答案,这些答案将作为数组中所述条目的子项列出,依此类推。

array(
array(
'id'=>0,
'headline'=>"My parent headline",
'body' =>"My parent body",
'children'=>array(
array(
'id'=>1,
'headline'=>"My firstChild headline",
'body' =>"My firstChild body",
'children'=>array()
),
array(
'id'=>2,
'headline'=>"My secondChild headline",
'body' =>"My secondChild body",
'children'=>array()
)
)
),
);

嵌套数组的深度是任意的,每个条目都有任意数量的 child 。对我来说,这是我想在模板范围内做的事情,因为我认为它是纯粹的显示逻辑。我不想在模板之外处理 HTML 或某种类型的 HTML 占位符。

我希望 smarty 将其打印为嵌套列表:

<ul>
<li>
<h1>My parent headline</h1>
<p>My parent body</p>
<ul>
<li>
<h1>My firstChild headline</h1>
<p>My firstChild body</p>
</li>
<li>
<h1>My secondChild headline</h1>
<p>My secondChild body</p>
</li>
</ul>
</li>
</ul>

我开始意识到这可能是一个非常具体的问题,所以我想我会写一个聪明的插件来专门处理这个问题,尽管我宁愿有一个全面的解决方案。

有办法吗?

最佳答案

在 Smarty 3 中,这可以使用 {function} 来完成。以下代码将产生所需的输出。

{function name=printList}
<ul>
{foreach $items as $item}
<li>
<h1>{$item['headline']}</h1>
<p>{$item['body']}</p>
{if $item['children']}
{call name=printList items=$item['children']}
{/if}
</li>
{/foreach}
</ul>
{/function}

{call name=printList items=$comments}

更多信息可以在 docs 找到.

旁注:仅仅因为某些东西是复杂的或递归的,并不意味着它不能在模板中。看在上帝的份上,HTML ul-li 结构自然是递归的,通过将其隐藏或将其移动到其他地方(只是因为它对于模板来说太复杂了),您正在为应用程序引入额外的复杂性。

关于php - 在 smarty 中处理递归的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/437862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com