I actually really like the Blade templating parser that Laravel ships with, but I know there are many who do not like it. Funny story about Blade, it was inspired and originates from .Net templating called Razor. Razor…Blade, get it? Razorblade.
Today we are going to be making Laravel use Twig instead of Blade. If you already use Twig in other PHP projects or come from a Django/Python background, then understandably you probably would want to use Twig over Blade. Different syntax but the same result.
We’re not going to be writing much code from scratch, instead we are going to be using a package called TwigBridge created by a crazy English man called Rob Crowe. This package will allow us to use Twig in our Laravel application and not only does it work, it is highly configurable.
- Open up your composer.json file (located in the root directory of your Laravel app) and add the following line to the require block:
Then in your command line terminal of choice type: composer update – this will not only install the TwigBridge package, it will also install Twig for us too, which is very nice of Rob. It means we need one less step.
Now we’ve got all of our needed packages installed, we need to tell Laravel about them. So open up the app/config/app.php file and look for the array list of providers and then add the following to the end:
- We’ve got TwigBridge and Twig installed, however we want to generate a configuration file so we can make our own changes (if need be). It’s not a requirement, but probably a good idea anyway. On your terminal console type: php artisan config:publish rcrowe/twigbridge – this will create a configuration file here: app/config/packages/rcrowe/twigbridge/config.php
That’s it. We’ve got Twig installed and don’t have to change a thing (except our template views). You call views using View::make like you’re already accustomed to doing.
Aliases and Helpers
The TwigBridge package is a gift that keeps on giving. By default it supports calling any aliased methods in our config/app.php file as well as any helper functions. You can read more about creating your own extensions and aliases here.