Skip to content

Instantly share code, notes, and snippets.

@rodrigopedra
Last active December 8, 2022 09:47
Show Gist options
  • Save rodrigopedra/4aa1b50a3ef1464d5ff8abc3daf97ace to your computer and use it in GitHub Desktop.
Save rodrigopedra/4aa1b50a3ef1464d5ff8abc3daf97ace to your computer and use it in GitHub Desktop.
Blade Optimizations
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\Compilers\BladeCompiler;
// @see https://laravel-news.com/faster-laravel-optimizations
class BladeServiceProvider extends ServiceProvider
{
public function register()
{
// This is needed as when compiling a string the footers are
// overwriten and the partials are processed before other templates
$this->app->singleton('partial.compiler', static fn ($app) => clone $app['blade.compiler']);
}
public function boot(BladeCompiler $blade)
{
$blade->directive('loop', static fn ($expression) => "<?php foreach ($expression): ?>");
$blade->directive('endloop', static fn () => '<?php endforeach; ?>');
$blade->directive('partial', function ($expression) {
$parts = \explode(',', $expression, 2);
$parts = \array_map(static fn ($string) => \trim($string), $parts);
$view = \trim($parts[0], '"\'');
$variables = $parts[1] ?? '[]';
$path = $this->app['view']->getFinder()->find($view);
$compiler = $this->app->make('partial.compiler');
$compiledPath = $compiler->getCompiledPath($path);
if (! \is_file($compiledPath)) {
$previousPath = $compiler->getPath();
$compiler->compile($path);
$compiler->setPath($previousPath);
}
$contents = $this->app['files']->get($compiledPath);
return <<<PHP
<?php call_user_func(function (\$__variables) use (\$__env) {
extract(\$__env->getShared(), EXTR_SKIP);
if (count(\$__variables)) extract(\$__variables);
?>
{$contents}
<?php }, {$variables}) ?>
PHP;
});
}
}
@rodrigopedra
Copy link
Author

rodrigopedra commented Oct 8, 2022

If someone figures out how to avoid having a second Blade compiler instance, please let me know :)

Kind of not possible right now due to this line:

https://github.com/laravel/framework/blob/1066e3955bfd0a7877707786efbf4fda9d450502/src/Illuminate/View/Compilers/BladeCompiler.php#L241

Currently overwrites BladeCompiler@$footer, which breaks if a partial is added inside a template using @extends

@rodrigopedra
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment