【问题标题】:Issue with Category tree in symfonysymfony 中的类别树问题
【发布时间】:2020-04-15 11:17:44
【问题描述】:

我在 symfony 5 中创建了一个类别树

我关注了:

Category.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:

出于某种原因,我不想要它。我该如何解决。谢谢。

【问题讨论】:

    标签: php symfony tree twig categories


    【解决方案1】:

    集合的行为似乎与数组不同。因为childrenArrayCollection,它总是会被设置。您应该检查它是否包含元素。

    {% if category.children is not empty %}
        <ul class="children">
            {{ macros.menu_categories(category.children) }}
        </ul>
    {% endif %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多