Back to Blog

How to use Twig in Laravel

/ Harrison Portwood

Twig is a templating engine that ships standard with the Symfony web framework. It employs a syntax closely resembling Django and Jinja templates, making it user-friendly and accessible for new developers, a crucial aspect of coding.

But it's 2023, and the PHP community has shown that it is more interested in Laravel than any other framework. The issue? Laravel comes standard with a different templating engine - Blade. But don't worry, plenty of creative minds have figured out how to leverage Twig with Laravel.

Composer

You only need to require one package:

Shell
composer require rcrowe/twigbridge

Laravel

Laravel will take care of most of the setup. Just use Artisan to publish the config file:

Shell
php artisan vendor:publish --provider="TwigBridgeServiceProvider"

From here, you can use Twig templates just like you do in Symfony:

PHP
public function index(Request $request) {
   $bar = 'foo'

   return view('my-twig-template', [
       'foo' => $bar
   ]);
}

Extending Twig Bridge

Let's say you have a list of states that you need rendered in your Twig template. Typically, constant values like these are kept in config/constants.php file provided by Laravel. For example:

PHP
return [
   'states' => [
       'Alabama' => 'AL',
       'Alaska' => 'AK'
       ...
   ]
]

So we'll extend the Twig functions class provided by Twig Bridge, then fetch these values and return them to the Twig template when the function is called.

You could edit config/twigbridge.php directly to add the new function, but since we like to keep code clean and organized, we'll create a new file named app/Twig/Functions.php and extend the function class from there:

PHP
<? php
namespace AppTwig;

use TwigExtensionAbstractExtension;
use TwigTwigFunction;

class Functions extends AbstractExtension {
   public function getFunctions() {
       return [
           new TwigFunction('states', [$this, 'states']),
       ];
   }

   public static function states() {
       // Default way to fetch constants in Laravel
       $states = config() -> get('constants.states')

       // Manipulate the data anyway you want!

       return $stateOptions;
   }
}

Then, enable your extension by adding the file to config/twigbridge.php:

PHP
'extensions' => [
   'enabled' => [
       ...
       'AppTwigFunctions'
   ]
]

Now you can use your function in the Twig templates:

Twig
<div>
   { { states() } }
</div >

This is a very simplified example that shows you the basics on extending Twig Bridge. With this information, you should have no issue using Twig with Laravel now. Get creative and make something awesome!