Render a Blade template from a Jigsaw event listener

Jigsaw (a statitc site generator) has 3 events you can listen to and run custom code when these events fire. One thing you may want to do in an event listener is render some HTML using a templating language. It makes sense to use Blade for this just like the rest of the project.

To do this, use BladeCompiler in bootstrap.php at the root directory of your Jigsaw project:

1<?php
2 
3use Illuminate\View\Compilers\BladeCompiler;
4use TightenCo\Jigsaw\Jigsaw;
5 
6 
7$events->afterBuild(function ($jigsaw) {
8 // get the Blade template as a string
9 $bladeTemplate = $jigsaw->readSourceFile('path/to/template.blade.php');
10 
11 // render the template
12 $renderedHTML = BladeCompiler::render($bladeTemplate, [
13 // data to pass to the template
14 ]);
15 
16 // write the file (path relative to the build directory)
17 $jigsaw->writeOutputFile('index.html', $renderedHTML)
18});

You're not going to automatically get all of Jigsaw's global variables though. You can pass a $page object with all your global config variables available as properties (mimicking what Jigsaw does when rendering a Blade template):

1$renderedHTML = BladeCompiler::render($bladeTemplate, [
2 'page' => $jigsaw->getConfig(),
3]);