Twig - 在父级中使用多个子模板
我有以下两个模板
parent.html
<ul class="basketItems">
{% for item in items %}
{{ item | raw }}
{% endfor %}
</ul>
child.html
<li>
<a href="/go/to/my/page">{{ link.title}}</a>
</li>
现在我想在parent.html 中有多个child.html 实例。在我的 php 代码中,我必须循环遍历子级并传入链接对象,以便可以填充 link.title 变量。
我当前的代码涉及加载parent.html,然后渲染每个子级并创建一个php数组,然后渲染parent.html并将所有生成的子级html作为数组条目传递(见下文)。有没有简单的方法可以做到这一点,而不必通过可能使用 Twig 块来构建 html 片段的 php 数组。
$parent = $twig->loadTemplate("parent.html");
foreach ($items as $item) {
$child = $twig->loadTemplate("child.html");
var $link = link::get($item->id));
/* do some other database retreival / data processing work */
$childHtml[] = $child->render(array('item' => $link));
}
$parent->render(array('items' => $childHtml));
提前致谢
I have the following two templates
parent.html
<ul class="basketItems">
{% for item in items %}
{{ item | raw }}
{% endfor %}
</ul>
child.html
<li>
<a href="/go/to/my/page">{{ link.title}}</a>
</li>
Now i would like to have multiple instances of child.html within parent.html. In My php code I have to loop through the children and pass in the link object so that the link.title variable can be populated.
My current code involves me loading in parent.html, then rendering each child and creating a php array, then rendering the parent.html and passing in all the generated html of the children as array entries (see below). Is there any easy way to do this without having to build up a php array of html snippets by possibly using Twig blocks.
$parent = $twig->loadTemplate("parent.html");
foreach ($items as $item) {
$child = $twig->loadTemplate("child.html");
var $link = link::get($item->id));
/* do some other database retreival / data processing work */
$childHtml[] = $child->render(array('item' => $link));
}
$parent->render(array('items' => $childHtml));
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
在手册中: http://twig.sensiolabs.org/doc/templates.html< /a>
对于 PHP 部分:
执行控制器操作并将干净的数组传递给模板引擎。不要混合那个。
最好遵循“关注点分离”原则:
http://en.wikipedia.org/wiki/Separation_of_concerns
try this:
Here in Manual: http://twig.sensiolabs.org/doc/templates.html
And for PHP Part:
Do the controller stuff and pass that clean array to template engine. Don't mix that.
It is always better to follow "Separation of concerns" principle:
http://en.wikipedia.org/wiki/Separation_of_concerns