Laravel Asset Pipeline with Twig

Ask any PHP dev about their asset pipeline and you’ll get all sorts of responses: Gulp. Grunt, Rails Gems, Assetic, no pipeline (naughty! 👿 ), or any mix of custom code that’s about as susceptible to code rot as a  newborn zombie.

Considering Laravel is essentially a layer of modernised sugar on top of Symfony components and other bits and bobs, it’s quite baffling that the framework  doesn’t feature an asset build pipeline out-of-the-box.

CodeSleeve’s asset-pipeline package, in my opinion, nails it. Simply put: there are configuration files that point to asset directories and there are include functions for your views. You don’t have to juggle different pre-compilation phases, the pipeline handles the lot: js, css, coffee, less, scsss, html, fonts  and images.

Caching is clever too: only files that have been changed force a compilation, so even local development trots along with the latest build.

To include compiled stylesheets and javascript files in a view you can use:

Let’s create a Twig extension inside the directory “YourNamespace/Twig/Extension” to wrap these calls in a simple function that we can invoke from any template.

Now we’ve built the extension, we need to give Twig the nod to include it.

Assuming you’ve installed TwigBridge, first run the artisan command:

php artisan config:publish rcrowe/twigbridge

Obviously you don’t have to run this if you have already done so for previous extension work.

Now we’ve got a “packages/rcrowe/twigbridge” folder in the config to override, edit the extensions.php file to include our new AssetPipelineExtension.

Now you’ll be able to sit back and let the pipeline do its thang as you include your assets via twig:

You can pimp this extension to include different manifests for different sections of a site (e.g. frontend/backend) but hopefully you get the point.

Anyway, thanks CodeSleeves and Happy Coding!

Laravel Asset Pipeline with Twig

t>