我正在尝试使用 Twig 模板,使用 Symfony 和 Doctrine 在博客上实现评论部分。
我在尝试为我的评论实现响应系统时遇到了一些问题。我想要这样的东西:
<div class="comment">
<p>This is comment number 1</p>
<div class="response">
<p>This is a response to comment number 1</p>
<div class="response">
<p>This is a response to response just above</p>
</div>
</div>
</div>
所以我想要一种嵌套的评论系统。
我有一个 Comment 实体,其 $response
属性与另一个 Comment 实体具有 OneToOne 关系:
/**
* @ORM\OneToOne(targetEntity="Comment")
*/
protected $response;
在我的 Controller 中,我只是得到这样的评论:
$comments = $this->getDoctrine()
->getManager()
->getRepository('AppBundle:Comment')
->findByArticle($article);
现在我正在尝试创建 HTML (Twig),但我不知道如何遍历所有评论和相关响应,以便我可以创建我在上面写的 HTML...
谁能帮我解决这个问题?
谢谢。
最佳答案
您所需要的只是重复。您有几个选项可供选择,其中之一是使用 macro .
用你的宏创建 Twig 文件:
{# src/AppBundle/Resources/views/Default/_macro.html.twig #}
{% macro print_comments_recursively(comment) %}
<div class="response">
<p>{{ comment }}</p> {# implement __toString on your Comment class or print appropriate property #}
{% if comment.response is not null %}
{{ _self.print_comments_recursively(comment.response) }}
{% endif %}
</div>
{% endmacro %}
在您的 View 中导入宏并使用它:
{% import 'AppBundle:Default:_macro.html.twig' as macros %}
<div class="comment">
<p>{{ comment }}</p>
{% if comment.response %}
{{ macros.print_comments_recursively(comment.response) }}
{% endif %}
</div>
这里你有类似的问题,已经用其他解决方案解决了:How to render a tree in Twig
关于php - Symfony-Doctrine 博客中用于嵌套评论的 Twig 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34582925/