显示文章的类别名称

Display the name of the category of an article

我是 symfony 和 Twig 的新手。我可以按类别显示我的文章,但我无法显示文章的类别名称。 我想显示一篇文章的类别名称,但我不能。 我确实喜欢这样,因为我有一个类别实体和一个文章实体: 谢谢你的帮助。

我的家庭控制器

    <?php

namespace App\Controller;

use App\Entity\Article;
use App\Entity\Category;
use App\Repository\ArticleRepository;
use App\Repository\CategoryRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class HomeController extends AbstractController
{
    private $repoArticle;
    private $repoCategory;

    public function __construct(ArticleRepository $repoArticle, CategoryRepository $repoCategory)
    {
        $this->repoArticle = $repoArticle;
        $this->repoCategory = $repoCategory;
    }

    /**
     * @Route("/", name="home")
     */
    //HOME
    public function index(CategoryRepository $repoCategory): Response

    {
        $repoArticle = $this->getDoctrine()->getRepository(Article::class);
        $repoCategory = $this->getDoctrine()->getRepository(Category::class);

        $categories = $repoCategory->findAll();
        // dd($repoCategory);

        $articles = $repoArticle->findAll();
        // dd($articles);   

        return $this->render("home/index.html.twig", [
            'articles' => $articles,
            'categories' => $categories,
        ]);
    }

    //SHOW
    /**
     * @Route("/show/{id}", name="show")
     */
    public function show($id): Response
    {

        $repoArticle = $this->getDoctrine()->getRepository(Article::class);

        $article = $repoArticle->find($id);
        // dd($articles);   

        if (!$article){
            return $this->redirectToRoute('home');
         }

        return $this->render("show/index.html.twig", [
            'article' => $article,
        ]);
    }

    //SHOW ARTICLE
    /**
     * @Route("/showArticles/{id}", name="show_article")
     */
    public function showArticle(?Category $category, Article $article): Response
    {
        // $articles = $category->getArticles()->getValues();
        // $catArticle = $article->getCategory()->getValues();
        // dd($catArticle);

        if($category){
            $articles = $category->getArticles()->getValues();
        }
        else{
            $articles = null;
            return $this->redirectToRoute('home');
        }
        $categories = $this->repoCategory->findAll();
        $catArticle = $article->getCategory()->getValues();
        return $this->render("home/index.html.twig", [
            'articles' => $articles,
            'categories' => $categories,
            'catArticle' => $catArticle,
        ]);
    }
}

我的index.html.twig

{% for article in articles %}
                <div class="col">
                    <div class="card p-0 col-md-4 mb-3" style="width: 25rem;">
                        <div class="cardImg">
                            <a href="{{ path('show', {'id':article.id}) }}"><img src="/assets/uploads/articles/{{ article.image }}" class="card-img-top roundedImg" alt="{{ article.image }}"></a>
                            <div class="caption">
                                {% for category in categories %}
                                {% if category.articles | length >=1 %}<span class="fontz-text glow">Category: {{ category.name }}</span>
                                {% else %}
                                {% endif %}
                                {% endfor %}
                              </div>
                        </div>
                    <div class="card-body">
                        <div class="card-header pb-0">
                            <p class="date smallText mb-3">Publié le: {{ article.createdAt | date("d/m/Y")}} à {{ article.createdAt | date("H:i")}} par {{ article.author }}</p>
                            <a href="{{ path('show', {'id':article.id}) }}"><h5 class="card-title pb-2">{{ article.title | u.truncate(50, '...', false)  }}</h5></a>
                            <p class="card-text txtDescription mb-3">{{ article.description | striptags | u.truncate(200, '...', false) }}</p>
                        </div>
                        {# <a href="" class="btn btn-fill-out mt-3 mb-5 w-100">En savoir plus</a> #}
                    </div>

                    </div>
                </div>  
                {% endfor %}

我的实体文章

    <?php

namespace App\Entity;

use App\Repository\ArticleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity(repositoryClass=ArticleRepository::class)
 */
class Article
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $title;

    /**
     * @ORM\Column(type="text")
     */
    private $description;

    /**
     * @ORM\Column(type="datetime_immutable")
     * @Gedmo\Timestampable(on="create")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime_immutable")
     * @Gedmo\Timestampable(on="update")
     */
    private $updatedAt;

    /**
     * @ORM\Column(type="boolean")
     */
    private $published;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $slug;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $tags;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $image;

    /**
     * @ORM\ManyToMany(targetEntity=Category::class, inversedBy="articles")
     */
    private $category;

    /**
     * @ORM\ManyToOne(targetEntity=User::class, inversedBy="articles")
     * @ORM\JoinColumn(nullable=false)
     */
    private $author;

    public function __construct()
    {
        $this->category = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getCreatedAt(): ?\DateTimeImmutable
    {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeImmutable $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeImmutable
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(\DateTimeImmutable $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    public function getPublished(): ?bool
    {
        return $this->published;
    }

    public function setPublished(bool $published): self
    {
        $this->published = $published;

        return $this;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

    public function getTags(): ?string
    {
        return $this->tags;
    }

    public function setTags(string $tags): self
    {
        $this->tags = $tags;

        return $this;
    }

    public function getImage(): ?string
    {
        return $this->image;
    }

    public function setImage(string $image): self
    {
        $this->image = $image;

        return $this;
    }

    /**
     * @return Collection|Category[]
     */
    public function getCategory(): Collection
    {
        return $this->category;
    }

    public function addCategory(Category $category): self
    {
        if (!$this->category->contains($category)) {
            $this->category[] = $category;
        }

        return $this;
    }

    public function removeCategory(Category $category): self
    {
        $this->category->removeElement($category);

        return $this;
    }

    public function getAuthor(): ?User
    {
        return $this->author;
    }

    public function setAuthor(?User $author): self
    {
        $this->author = $author;

        return $this;
    }
}

我的实体类别

    <?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\Column(type="string", length=255, nullable=true)
     */
    private $description;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $image;

    /**
     * @ORM\ManyToMany(targetEntity=Article::class, mappedBy="category")
     */
    private $articles;

    public function __construct()
    {
        $this->articles = 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 getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(?string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getImage(): ?string
    {
        return $this->image;
    }

    public function setImage(string $image): self
    {
        $this->image = $image;

        return $this;
    }

    /**
     * @return Collection|Article[]
     */
    public function getArticles(): Collection
    {
        return $this->articles;
    }

    public function addArticle(Article $article): self
    {
        if (!$this->articles->contains($article)) {
            $this->articles[] = $article;
            $article->addCategory($this);
        }

        return $this;
    }

    public function removeArticle(Article $article): self
    {
        if ($this->articles->removeElement($article)) {
            $article->removeCategory($this);
        }

        return $this;
    }
    public function __toString()
    {
        return $this->name;
    }
}

您的类别有很多,因此显示所有文章类别会像这样:

{% for category in article.category %}
   <span class="fontz-text glow">Category: {{ category.name }}</span>
{% endfor %}

对于一个类别,您可以这样做:

<span class="fontz-text glow">Category: {{ article.category[0].name }}</span>