How to view pages on Symfony 6

How to view pages on Symfony 6

Posted by Ervin Adams on May 6, 2022

This tutorial will go through viewing pages when developing your Symfony project, if your using a development packages such as Wamp or Xampp.

Step 1. Create a controller.

Create a controller called HomeController.

Go to “/src/HomeController.php” and edit to look like below snippet:

<?php


namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class HomeController extends AbstractController
{

    /**
     * @Route("/home", name="home")
     */
    public function index(): Response
    {

        return $this->render('index.html.twig', [
            'controller_name' => 'HomeController',
        ]);
    }
}

Step 2. Create view page

Create a view called index.

Go to “/templates/index.html.twig” and edit to look like below snippet:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>home</title>
</head>
<body>
    <h1>I am home</h1>
</body>
</html>

Step 3. Start server 

If you do not have .htaccess file installed, start the server and go to "http://localhost/thenameofyourproject/public/index.php/home"

Just replace the part in the url that says thenameofyourproject with your project name.

Step 4. remove index.php from url

In order to remove the index.php from the url, you can use a .htaccess file.

run command from the root of project below:

composer require symfony/apache-pack

You should see an .htaccess file in "/public/.htaccess"

Now you should be able to use this url "http://localhost/thenameofyourproject/public/home"