petervandijck's avatar

Code review request: using @markdown in Blade

To use Markdown within Blade templates like this

@markdown

# A first-level heading
## A second-level heading
### A third-level heading
- bullet
- bullet

@endmarkdown

I did the following. It works, but would like any feedback on the code.

In AppServiceProvider, I added

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Str;

Then in the boot() method in AppServiceProvider:

Blade::directive('markdown', function () {
          return "Hello <?php echo(Str::markdown(<<<HEREDOC";
});

Blade::directive('endmarkdown', function () {
            return "HEREDOC)); ?>";
});

And finally, on the command line:

php artisan view:clear 

Any feedback or comments to make this nicer/better?

0 likes
5 replies
hupp's avatar

@petervandijck This was good. You can do one step ahead to make Custom Blade Directives Service Provider. and move this code into that file. and in config/app.php you have to include and use it regular blade directive.

return [
    // ...
    'providers' => [
        // Other service providers...
        App\Providers\CustomBladeDirectivesServiceProvider::class,
    ],
    // ...
]; 
1 like
webrobert's avatar

hmmm, I like the class component version better because the css can be wrapped up in the component blade and the class itself can handle the markdown. Then you just end up with...

<x-markdown>

# A first-level heading
## A second-level heading
### A third-level heading
- bullet
- bullet

</x-markdown>
1 like

Please or to participate in this conversation.