显示文章类别的名称

Posted

技术标签:

【中文标题】显示文章类别的名称【英文标题】:Display the name of the category of an article 【发布时间】:2021-12-24 16:48:43 【问题描述】:

我是 symfony 和 Twig 的新手。我可以按类别显示我的文章,但我不能显示文章的类别名称。 我想显示一篇文章的类别名称,但我不能。 知道我有一个 Category 实体和一个 Article 实体,我确实喜欢这样: 感谢您的帮助。

我的家庭控制器

    <?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" ></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;
    

【问题讨论】:

您能分享您的类别和文章实体吗?希望你已经在这两个实体之间建立了关系,如果这样的话,显示它会很容易 【参考方案1】:

您的类别有很多对很多,因此显示所有文章类别将是这样的:

% 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>

【讨论】:

非常感谢

以上是关于显示文章类别的名称的主要内容,如果未能解决你的问题,请参考以下文章

在单个文章中将类别名称显示为不带链接的页面标题(仅名称)

一起显示所有类别名称 woocommerce

使用 onChange 从 <select> 标记更新状态并过滤类别列表以显示该类别的博客文章

多个类别名称未显示通知内容扩展?

如何获取类别、文章和子类别及其文章?

在 WooCommerce 中随处显示商品名称下的产品类别和“品牌”属性术语名称