Skip to content

Commit

Permalink
expand blade extension example
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Jun 2, 2015
1 parent 61de134 commit 7d992b2
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions blade.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,13 +202,39 @@ The `@inject` directive may be used to retrieve a service from the Laravel [serv
<a name="extending-blade"></a>
## Extending Blade

Blade even allows you to define your own custom directives. You can use the `directive` method to register a directive. When the Blade compiler encounters the directive, it calls the provided callback with its parameter. This allows you to replace your directives with any logic as complex as you want.
Blade even allows you to define your own custom directives. You can use the `directive` method to register a directive. When the Blade compiler encounters the directive, it calls the provided callback with its parameter.

The following example creates a `@datetime($var)` directive which formats a given `$var`:

Blade::directive('datetime', function($expression) {
return "<?php echo with{$expression}->format('m/d/Y H:i'); ?>";
});
<?php namespace App\Providers;

use Blade;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
Blade::directive('datetime', function($expression) {
return "<?php echo with{$expression}->format('m/d/Y H:i'); ?>";
});
}

/**
* Register bindings in the container.
*
* @return void
*/
public function register()
{
//
}
}

As you can see, Laravel's `with` helper function was used in this directive. The `with` helper simply returns the object / value it is given, allowing for convenient method chaining. The final PHP generated by this directive will be:

Expand Down

0 comments on commit 7d992b2

Please sign in to comment.