【发布时间】:2020-10-07 17:35:29
【问题描述】:
在我的 twig 中,我想在 url 中传递我的类别名称以查看该类别的详细信息。
在我的控制器中,我把它作为一个路由:
**
* @Route("/{name}", name="category_name", methods={"GET"})
*/
public function categorie(CategoryRepository $categoryRepository): Response
{
return $this->render('category/index.html.twig', [
'categories' => $categoryRepository->findAll(),
]);
}
之后,我把它放在我的树枝中以获得名称的第一个值:
{% for test in tests %}
{% set array = test.categories|join(' - ')|split(' ', 2) %}
<div class="category"><a href="{{ path('category_name', {'name': attribute(array, 0)}) }}">{{ attribute(array, 0) }}</a></div>
{% endfor %}
我的测试课:
<?php
namespace App\Entity;
use App\Repository\TestRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=TestRepository::class)
*/
class Test
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $title;
/**
* @ORM\Column(type="text")
*/
private $content;
/**
* @ORM\ManyToMany(targetEntity=Category::class, inversedBy="test_category")
*/
private $categories;
}
我的分类类:
<?php
namespace App\Entity;
use App\Repository\CategoryRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=CategoryRepository::class)
*/
class Category
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @ORM\ManyToMany(targetEntity=Test::class, mappedBy="categories")
*/
private $test_category;
}
但我有这个错误信息:
在渲染模板期间引发了异常(“路由“category_name”的“参数“name”必须匹配“[^/]++”(“”给定)以生成相应的URL。”)。
【问题讨论】:
-
只是第一个结果?
categories.0.name工作吗?当然,您只能从您的控制器传递第一个结果。但我不得不说,我不知道tests是什么,也不知道它来自哪里。 -
categories.0.name不起作用。我在主帖中添加了我的测试和类别类。 -
test.categories|join(' - ')|split(' ', 2)[0]应该可以工作... -
总是同样的错误信息...
-
可能是你根本没有分类?或者类别没有名称,或者名称以空格开头?