Laravel Articles
Laravel Videos
General Articles
YouTube Journey Series
11th February 2021 • Laravel
When it comes to optimising your website for performance, embedding core, essential CSS in the head of your HTML can have a small impact. In doing so you can load initial styles immediately while your main CSS is loaded.
This is great, but it clutters up your HTML head. You could have a blade template dedicated to this, and include it in the head like so:
@include('includes.styles')
But, you now have a blade template file that just has CSS in it. It makes sense to have your CSS in .css
files. Plus, if you're using a CSS pre-processor like SASS you can't have that in a blade template.
So wouldn't it be nicer if we had a separate CSS file which we could reference, and blade embeds the contents of that file into the head for us?
Sounds like a job for Blade!
To add a custom directive we need to add some code to the boot
method in our App\Providers\AppServiceProvider
.
Essentially what we want to do is pass in the path to our CSS file, and use PHP's get_file_contents()
function to echo the contents of the file.
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
...
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Blade::directive('embedstyles', function ($expression) {
return "<style><?php echo file_get_contents($expression); ?></style>";
});
}
}
As you can see above, we've declared a new directive using the directive
method on the Blade
facade. We've named it embedstyles
and in the callback we return the PHP code to display the contents of the file.
Pretty simple stuff really!
Now, in our HTML head we can use the directive to include our essential CSS.
@embedstyles('css/core.css')
I hope you enjoyed this article. I'm currently working on a project that had this exact requirement, so I thought it would be a good example of a custom blade directive. As always, if you have any feedback, questions or just want to chat about code you can find me on Twitter @CodingWithStef, and on my YouTube channel.
Until next time!