[英]how to display comments in twig recursively
我在树枝上显示评论有问题。 如果我将它们全部列出,则它们是可见的,但我需要将它们嵌套。
这是实体,我认为应该像这样引用:
/**
* @var \AppBundle\Entity\Comment
*
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Comment")
* @ORM\JoinColumn(name="parentId", referencedColumnName="id")
*/
private $parentId;
控制器很简单,从db获取所有注释,并返回array(带有和不带有parentId)按照以下说明,我将其添加到主树枝文件中:
<!-- Comments and omments with parentId -->
{% include 'front/main/comments-main.html.twig' with {'commments':comments} %}
列出所有评论的作品。 但是在包含的树枝中,似乎这种代码的安宁
{% if comment.parentId != null %}
{% set children = [] %}
{% set children = children|merge([ comment ]) %}
{% include 'front/main/comments-main.html.twig' with {'comments':children} %}
{% endif %}
不起作用。 如果我有回应,它会显示在正确的位置,并带有该ID的评论下。 但是如果没有,那条线就在里面。 页面加载非常慢,并且永远不会结束。 就像无限循环。 我做错了什么?
好吧,我做到了。 这是无限循环的问题,但是因为我正在处理parentId,并且正在遵循某个正在处理object.children的人的指示。 所以我必须使自己成为多对一的自我导向
// ...
/**
* One Category has Many Categories.
* @OneToMany(targetEntity="Category", mappedBy="parent")
*/
private $children;
/**
* Many Categories have One Category.
* @ManyToOne(targetEntity="Category", inversedBy="children")
* @JoinColumn(name="parent_id", referencedColumnName="id")
*/
private $parent;
// ...
public function addChild(Comment $child) {
$this->children[] = $child;
$child->setParentId($this);
}
public function __construct() {
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
(摘自http://docs.doctrine-project.org/projects/doctrine-orm/zh-CN/latest/reference/association-mapping.html#one-to-many-self-referencing )并在设置子代。flush()之前
$parent = $comment->getParentId();
$parent->addChild($comment);
在树枝中,我已经有了子模板,在循环内
<div>
{% if comment.children is defined %}
{% include 'front/main/comments-main.html.twig' with {'comments':comment.children} %}
{% endif %}
</div>
希望能节省一些时间给某人,我却浪费了数小时!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.