php - Symfony-Doctrine 博客中用于嵌套评论的 Twig 循环

标签 php doctrine-orm twig symfony

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

我在尝试为我的评论实现响应系统时遇到了一些问题。我想要这样的东西:

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

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

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

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

在我的 Controller 中,我只是得到这样的评论:

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

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

谁能帮我解决这个问题?

谢谢。

最佳答案

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

用你的宏创建 Twig 文件:

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

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

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

关于php - Symfony-Doctrine 博客中用于嵌套评论的 Twig 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34582925/

相关文章:

php - SQLSTATE[HY000] [2002] 连接被拒绝 - MAMP & Symfony 2

symfony - 使用 Doctrine 为每个 fork 子进程单独的数据库连接

php - Doctrine 2 在 MVC ZF2 环境中扮演什么角色?

php - 如何通过 Twig path() 函数传输 POST 变量

php - 使用 rand() 从 MySQL 生成唯一的随机元素

php - 使用 TWIG 加载远程文件

php - PDOstatement有问题,其中不包含应包含的内容

javascript - ajax上传图片不起作用

symfony - 错误 : You cannot create a service ("templating.helper.assets") of an inactive scope ("request")

javascript - ajax symfony 中的 Concat 变量