DEV Community

Recca Tsai
Recca Tsai

Posted on • Originally published at recca0120.github.io

Render Markdown with Blade and Embed Dynamic Syntax

Originally published at recca0120.github.io

The Idea

Writing documentation in Markdown is convenient. It would be even better if you could embed Blade syntax (like @include or variables) inside the Markdown files. Laravel's Blade engine supports custom file extensions, so you can have it process .md files as well.

Implementation

Install a Markdown Package

Install league/commonmark:

composer require league/commonmark
Enter fullscreen mode Exit fullscreen mode

Controller

The example below uses league/commonmark v2 (v1 has a different API):

use Illuminate\View\Factory;
use League\CommonMark\GithubFlavoredMarkdownConverter;

class DocsController extends Controller
{
    private $viewFactory;

    public function __construct(Factory $viewFactory)
    {
        $this->viewFactory = $viewFactory;
        // Let .md files be processed by the Blade engine
        $this->viewFactory->addExtension('md', 'blade');
    }

    public function index() {
        $converter = new GithubFlavoredMarkdownConverter([
            'allow_unsafe_links' => false,
        ]);

        // First compile through Blade, then convert to HTML
        return $converter->convert($this->viewFactory->make('demo.md'));
    }
}
Enter fullscreen mode Exit fullscreen mode

The flow is: Blade first processes the variables and directives in demo.md, outputs a plain Markdown string, then CommonMark converts it to HTML.

Top comments (0)