I
I
Ilya Loopashko2020-10-04 09:34:06
symfony
Ilya Loopashko, 2020-10-04 09:34:06

How to display all posts of a certain category?

How to display all posts of a certain category?

Error in this snippet

/**
     * @Route("/category/{category}", name="category")
     */
    public function category(Category $category)
    {
        return $this->render('default/category.html.twig', [
            'category'=>$category

        ]);


DefaultController.php
<?php

namespace App\Controller;

use App\Entity\Category;
use App\Entity\Menu;
use App\Entity\Post;
use App\Entity\Tag;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;


class DefaultController extends AbstractController


{
    /**
     * @Route("/default", name="default")
     */
    public function index()
    {

        $em = $this->getDoctrine()->getManager();
        $post = $em->getRepository(Post::class)->findAll();
        $menu = $em->getRepository(Menu::class)->findAll();
        $category = $em->getRepository(Category::class)->findAll();
        $tag = $em->getRepository(Tag::class)->findAll();


        return $this->render('default/index.html.twig', [
            'controller_name' => 'DefaultController',
            'post'=>$post,
            'category'=>$category,
            'tag'=>$tag,
            'menu'=>$menu

        ]);

    }

    /**
     * @Route("/post/single/{post}", name="single")
     */
    public function single(Post $post)
    {
        return $this->render('default/single.html.twig', [
            'post'=>$post

        ]);
    }

    /**
     * @Route("/category/{category}", name="category")
     */
    public function category(Category $category)
    {
        return $this->render('default/category.html.twig', [
            'category'=>$category

        ]);
    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-10-04
@deadloop

Something like this if the Post has a category property

/**
 * @Route("/category/{category}", name="category")
 */
public function category(Category $category)
{
    return $this->render('default/category.html.twig', [
        'category' => $category,
        'posts' => $this->getDoctrine()->getManager()->getRepository(Post::class)->findBy(['category' => $category])
    ]);
}

Then iterate over the posts in the template.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question