【问题标题】:how to display comments in twig recursively如何递归地在树枝中显示评论
【发布时间】:2017-09-29 12:46:06
【问题描述】:

我在树枝上显示 cmets 有问题。如果我将它们全部列出,它们是可见的,但我需要将它们嵌套。

这是实体,我认为应该这样引用它:

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

Controller 很简单,从 db 中获取所有 cmets 并返回数组(有和没有 parentId) 按照一些说明,我将其添加到主树枝文件中:

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

列出所有 cmets 有效。但在包含的树枝中,这似乎是代码的平静

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

不起作用。如果我回显某些内容,它会显示在正确的位置,并在带有该 ID 的注释下。但是如果没有的话,里面有那条线。页面加载非常缓慢并且永远不会结束。就像无限循环。我做错了什么?

【问题讨论】:

  • 您需要与macro's 合作来解决这个问题,看看这个answer
  • 我关注了这个stackoverflow.com/questions/8326482/…。来自 random-coder-1920 的第一个答案。他在使用宏和不使用宏时都这样做了。我将不得不尝试宏....
  • 是的,但他正在使用子模板来包含。您再次包含整个模板,导致无限循环。 macro's 只是更清洁地解决了这个问题(并且可重复使用)

标签: php symfony twig


【解决方案1】:

嗯,我做到了。这是无限循环的问题,但因为我正在处理 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/en/latest/reference/association-mapping.html#one-to-many-self-referencing) 并在控制器中进行小改动以设置 children.Before 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>

希望为某人节省几分钟,我浪费了几个小时!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 2021-10-29
    相关资源
    最近更新 更多