Skip to content

Instantly share code, notes, and snippets.

@loilo

loilo/buffer.php

Created Apr 11, 2020
Embed
What would you like to do?
Output Buffering Directive for Laravel Blade Templates

Output Buffering Directive for Laravel Blade Templates

This is a simple output buffering directive for Laravel's Blade templating engine. It can be used to buffer output (e.g. from other directives) into a variable.

The @buffer directive starts buffering output, the @endbuffer directive stops it. @endbuffer also takes a variable name as an optional parameter to store the buffered output in. If no variable name is provided, all buffered output will be discarded.

The concrete example that sparked the idea for this directive was to take a Blade template with SVG contents and use it as a Base64 encoded SVG favicon — like this:

@buffer
@include('icons.laravel', [ 'fill' => '#ff2d20' ])
@endbuffer('icon')
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,{{ base64_encode($icon) }}" sizes="any">
<?php
// In your AppServiceProvider's boot() method, put this:
Blade::directive('buffer', function () {
return '<?php ob_start(); ?>';
});
Blade::directive('endbuffer', function (string $name) {
if ($name === '') {
return '<?php ob_end_clean(); ?>';
} else {
$name = preg_replace('/^(["\'])(.+)\1$/', '$2', $name);
if (!preg_match('/^[a-z][0-9a-z_]*$/i', $name)) {
throw new UnexpectedValueException(sprintf(
'Invalid variable name "%s" to hold buffered content',
$name
));
}
return "<?php $$name = ob_get_contents(); ob_end_clean(); ?>";
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.