2017-09-29 5 views
1

twigのコメント表示に問題があります。私はそれらをすべて列挙すれば表示されますが、入れ子にする必要があります。twigで再帰的にコメントを表示する方法

これが実体である、私はそれがこのように参照する必要があると思った:

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

コントローラはシンプルですが、私はこれを追加いくつかの命令の次の(と、と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でコメントの下で適切な場所に表示されます。しかし、もしそうでなければ、その中にその行があります。ページの読み込みが非常に遅く、終了しません。無限ループのように。私が間違っていることは何ですか?

+4

あなたはこのを見て、これを解決するためにmacro's' 'と連携する必要があります[解答](https://stackoverflow.com/questions/45955614/multi-level-menu-with-twig/45956255# 45956255) – DarkBee

+0

私はこのhttps://stackoverflow.com/questions/8326482/how-to-render-a-tree-in-twigに従っていました。ランダムコーダ-1920からの最初の答え。彼はマクロと無しの両方でそれをやった。私はマクロを試す必要があります.... –

+0

はい、しかし、彼は含まれるためにサブテンプレートを使用しています。テンプレート全体をもう一度含めて、無限ループになります。 'マクロ'はこれを解決するためにちょっとだけ洗っています(再利用可能です) – DarkBee

答えて

0

さて、私はそれをしました。無限ループの問題でしたが、私はparentIdを扱っていたので、object.childrenを扱っていた人の指示に従っていました。だから私は関係が1つの自己方向に多くのことをしなければならなかった

// ... 
/** 
* 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/en/latest/reference/association-mapping.html#one-to-many-self-referencingから)

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

そして中children.Beforeのフラッシュを()に設定するのcontrolerに小さな変更を行うには私が既に持っていたサブテンプレートで、ループ内にあった

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

時間を失ってしまいました。