Set Default Path for Twig Templates in Symfony 6

Set Default Path for Twig Templates in Symfony 6

In Symfony application, Twig templates are stored in the templates directory by default.There might be required to store the Twig templates in different location. This tutorial shows how to set default path for Twig templates in Symfony 6 application.

The default templates directory can be configured using the default_path option under the twig key:

config/packages/twig.yaml

twig:
    default_path: '%kernel.project_dir%/client_templates'

Now Symfony will look Twig templates in the specified directory by default. In order to test create the controller and template in new directory.

client_templates/test/index.html.twig

{{ 'Testing new default directory' }}

src/Controller/TestController.php

<?php

namespace App\Controller;

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

class TestController extends AbstractController
{
    #[Route('/')]
    public function index(): Response
    {
        return $this->render('test/index.html.twig');
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.