Skip to content

Instantly share code, notes, and snippets.

@paulredmond
Last active July 12, 2017 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulredmond/8ba3c45e0374dc1fd775fe91b92b93e9 to your computer and use it in GitHub Desktop.
Save paulredmond/8ba3c45e0374dc1fd775fe91b92b93e9 to your computer and use it in GitHub Desktop.
Example Blade Extension class to group Blade conditionals and directives...
<?php
/**
* This interface would be provided by the framework and properly namespaced
* This is just an example of what an interface might be like...
*/
interface BladeExtension
{
public function getDirectives();
public function getConditionals();
}
<?php
/**
* Example blade extension class for grouping extensions
*/
class ExampleBladeExtension implements BladeExtension
{
public function getDirectives()
{
return [
'truncate' => [$this, 'truncate']
];
}
public function getConditionals()
{
return [
'prod' => [$this, 'isProduction']
];
}
public function isProduction()
{
return app()->environment('production');
}
/**
* @see https://zaengle.com/blog/exploring-laravels-custom-blade-directives
*/
public function truncate($expression)
{
list($string, $length) = explode(',',str_replace(['(',')',' '], '', $expression));
return "<?php echo e(strlen({$string}) > {$length} ? substr({$string},0,{$length}).'...' : {$string}); ?>";
}
}
<?php
/**
* This isn't properly namespaced, just an example service provider
* @see https://laravel.com/docs/5.4/providers
*/
class MyServiceProvider
{
public function register()
{
// Service container available to extensions
$this->app->bind('ExampleBladeExtension', function ($app) {
return new ExampleBladeExtension();
});
$this->app->tag(['ExampleBladeExtension'], 'blade.extension');
}
}
// Laravel would then grab all these out of the container (not in this file), including packages,
// and register them properly with blade 👍
collect($this->app->tagged('blade.extension'))->each(function ($extension) {
// register directives with callables - $extension->getDirectives()
// register Blade::if() with callables - $extension->getConditionals()
});
@paulredmond
Copy link
Author

I dig how you register twig extensions in Symfony through the container - https://symfony.com/doc/current/templating/twig_extension.html

@paulredmond
Copy link
Author

paulredmond commented Jul 12, 2017

These are just some ideas, not real working code. Sometimes I like grouping related extensions .

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