简体   繁体   中英

how to display comments in twig recursively

I have problem with comments display in twig. They are visible if I list them all but I need them to be nested.

This is entity, I thought it should be referenced like this:

/**
 * @var \AppBundle\Entity\Comment
 * 
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Comment")
 * @ORM\JoinColumn(name="parentId", referencedColumnName="id")
 */
private $parentId;

Controller is simple, fetch all comments from db and returns array( with, and without parentId) Following some instruction i added this to main twig file:

<!-- Comments and omments with parentId -->
{% include 'front/main/comments-main.html.twig' with {'commments':comments} %}

Listing all comments works. But in included twig it seems this peace of code

{% if comment.parentId != null %}
            {% set children = [] %}
            {% set children = children|merge([ comment ]) %}
            {% include 'front/main/comments-main.html.twig' with {'comments':children} %}
        {% endif %}

does not work. If I echo something it is displayed in the right place, under comment with that id. But with that lines inside if not. Page load very slow and never ends. Like infinite loop. What I am doing wrong?

Well, I did it. It was problem with infinite loop but because I was dealing with parentId, and I was following instructions of a someone who was dealing with object.children. So I had to make relation to be Many to One self-directional

// ...
/**
 * 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();
}

(from http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-self-referencing ) And to make small change in controler to set children.Before flush()

        $parent = $comment->getParentId();
        $parent->addChild($comment);

And in twig, in subtemplate I already had, inside the loop

<div>
    {% if comment.children is defined %}
        {% include 'front/main/comments-main.html.twig' with {'comments':comment.children} %}
    {% endif %}
</div>

Hope to save some minutes to someone, I lost hours!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM