Я создал дерево категорий в symfony 5
У меня есть следующие данные:
Категория. php Объект:
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Category", inversedBy="children")
*/
private $parent;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Category", mappedBy="parent")
*/
private $children;
public function __construct()
{
$this->children = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getParent(): ?self
{
return $this->parent;
}
public function setParent(?self $parent): self
{
$this->parent = $parent;
return $this;
}
/**
* @return Collection|self[]
*/
public function getChildren(): Collection
{
return $this->children;
}
public function addChild(self $child): self
{
if (!$this->children->contains($child)) {
$this->children[] = $child;
$child->setParent($this);
}
return $this;
}
CategoryReponsitory. php
public function getAllCategory()
{
$query = $this->createQueryBuilder('c')
->where('c.parent IS NULL');
return $query->getQuery()->getResult();
}
Контроллер. php
public function index(CategoryRepository $categoryRepository): Response
{
return $this->render('category/index.html.twig', [
'categories' => $categoryRepository->getAllCategory(),
]);
}
И файл шаблона веточки index.html.twig
{% macro menu_categories(categories) %}
{% import _self as macros %}
{% for category in categories %}
<li>
<a href="cate/{{ category.id }}">{{ category.name }}</a>
{% if category.children %}
<ul class="children">
{{ macros.menu_categories(category.children) }}
</ul>
{% endif %}
</li>
{% endfor %}
{% endmacro %}
<ul class="menu-category">
{{ _self.menu_categories(categories) }}
</ul>
Он правильно рендерит, но если дети У меня нет детей, она по-прежнему отображает html, как показано ниже:
![enter image description here](https://i.stack.imgur.com/3P6Ka.png)
Я не хочу этого по некоторым причинам. Как я могу это исправить. Спасибо.