2

I am trying to implement a comment section on a blog with Symfony and Doctrine, using Twig templates.

I am having some trouble trying to implement a response system for my comments. I would like to have something like this:

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

So I would like to have sort of a nested comment system.

I have a Comment entity with a $response property having a OneToOne Relation with another Comment entity:

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

In my controller, I just get my comments like this:

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

Now I am trying to create the HTML (Twig) but I don't know how to loop throught all comment and associated response so I can create the HTML as I wrote just above...

Anyone who can help me with that?

Thanks.

user2108742
  • 117
  • 12

1 Answers1

7

All you need is recurrence. You have a few options to choose from, one of them is using a macro.

Create twig file with your 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 macro in your view and use it:

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

Here you have similar problem, already solved, with other solutions: How to render a tree in Twig

Community
  • 1
  • 1
biera
  • 2,608
  • 1
  • 24
  • 26