【问题标题】:Twig loop for nested comment in a Symfony-Doctrine blogSymfony-Doctrine 博客中嵌套评论的 Twig 循环
【发布时间】:2016-01-03 23:41:13
【问题描述】:

我正在尝试使用 Twig 模板在博客上使用 Symfony 和 Doctrine 实现评论部分。

我在尝试为我的 cmets 实施响应系统时遇到了一些麻烦。我想要这样的东西:

<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>

所以我想要一个嵌套的评论系统。

我有一个带有 $response 属性的 Comment 实体,该属性与另一个 Comment 实体具有 OneToOne 关系:

/**
 * @ORM\OneToOne(targetEntity="Comment")
 */
protected $response;

在我的控制器中,我的 cmets 是这样的:

$comments = $this->getDoctrine()
                    ->getManager()
                    ->getRepository('AppBundle:Comment')
                    ->findByArticle($article);

现在我正在尝试创建 HTML (Twig),但我不知道如何遍历所有评论和相关响应,因此我可以创建上面写的 HTML...

谁能帮我解决这个问题?

谢谢。

【问题讨论】:

    标签: php doctrine-orm twig symfony


    【解决方案1】:

    您所需要的只是重复。您有几个选项可供选择,其中之一是使用 macro。

    用你的宏创建树枝文件:

    {# 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 %}
    

    在您的视图中导入宏并使用它:

    {% 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

    【讨论】:

    • 很好的解决方案!谢谢
    猜你喜欢
    • 2020-06-01
    • 2021-04-16
    • 1970-01-01
    • 2021-09-09
    • 2013-04-16
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 2018-03-08
    相关资源
    最近更新 更多