use*_*742 1 php symfony doctrine-orm twig
我正在尝试使用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>
Run Code Online (Sandbox Code Playgroud)
所以我想有一个嵌套的评论系统.
我有一个Comment实体,其$response属性与另一个Comment实体具有OneToOne关系:
/**
* @ORM\OneToOne(targetEntity="Comment")
*/
protected $response;
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我只是得到这样的评论:
$comments = $this->getDoctrine()
->getManager()
->getRepository('AppBundle:Comment')
->findByArticle($article);
Run Code Online (Sandbox Code Playgroud)
现在我正在尝试创建HTML(Twig),但我不知道如何遍历所有注释和相关的响应,因此我可以创建HTML,就像我上面写的那样......
有谁可以帮助我吗?
谢谢.
你需要的只是复发.您有几个选项可供选择,其中一个是使用宏.
使用您的宏创建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 %}
Run Code Online (Sandbox Code Playgroud)
在视图中导入宏并使用它:
{% 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>
Run Code Online (Sandbox Code Playgroud)
在这里你有类似的问题,已经解决了,与其他解决方案:如何在Twig中渲染树
| 归档时间: |
|
| 查看次数: |
675 次 |
| 最近记录: |