Render files from the command line with Blade

Packages

June 10th, 2022

blade-cli-featured.png

With the Laravel Blade CLI package, you can use the Blade engine to render files from the command line. This package doesn't support 100% of all Blade directives you might be familiar with in Laravel but does support common ones like @if, @else, @foreach, @forelse, @while, etc.

Give the following example file from the readme:

1name: {{ $name }}
2relationship: {{ $relationship }}
3favorite_food: {{ $favoriteFood }}
4@if($includeAddress)
5address: "123 example lane"
6@endif

You can render that file using the CLI:

1blade render ./person.yml \
2 --name="Bob" \
3 --relationship="Uncle" \
4 --favorite-food="Pizza" \
5 --include-address \
6 --save-directory="build/"

Which will save the file at ./build/person.yml

Installing this project globally via composer gives you access to the blade CLI command. However, you can also use the code directly from this package:

1use BladeCLI\Blade;
2use Illuminate\Container\Container;
3use Illuminate\Filesystem\Filesystem;
4 
5$blade = new Blade(
6 container: new Container,
7 filesystem: new Filesystem,
8 filePath: '/path/to/file/to/render',
9 options: [
10 'force'=> true, // force overwrite existing rendered file
11 'save-directory'=>'save-to-dir' // optional directory to save rendered file to. Default is current directory.
12 ]
13);
14 
15// render the file with this data/vars
16$blade->render([
17 'var'=>'example'
18]);

You can also pass data to the template via JSON using the --from-json flag, which accepts a path to a JSON file. Finally, you can use this package to process an entire directory of templates:

1php blade render templates/ --some-data=foo --force

You can learn about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.

Laravel News Partners