How to Use Blade Component to Render Markdown in Laravel

How to Use Blade Component to Render Markdown in Laravel cover image

Spatie launched Laravel Markdown which is a Powerful markdown renderer and Blade component for Laravel. This package includes a blade component that can render markdown and a highly configurable class that can be utilized to render markdown.

Requirements

This package requires:

  1. PHP 8 or higher

  2. For highlighting code: Node 10 or newer

Installation & Setup

You’ve to run this command for the installation via composer.

composer require spatie/laravel-markdown

You can enable the code highlighting feature by installing the JavaScript package Shiki in your laravel project.

You’ve to run this command for the installation via npm.

npm install shiki

Ensure that you have installed Node 10 or higher.

You can publish the config file with this command:

php artisan vendor:publish --provider="Spatie\LaravelMarkdown\LaravelMarkdownBladeCom

Usage

Let’s begin with an example of the given x-markdown Blade component.

<x-markdown>
# My title
It is a [link to our website](https://spatie.be)

``
php
echo 'Hello world';
``
</x-markdown>

The above chunk of markdown will be transformed to this chunk of HTML:

<div>
    <h1 id="my-title">My title</h1>
    <p>This is a <a href="https://spatie.be">link to our website</a></p>
    <pre class="shiki" style="background-color: #fff"><code><span class="line"><span
        style="color: #005CC5">echo</span><span style="color: #24292E"> </span><span style="color: #032F62">&#39;Hello world&#39;</span>
	<span
        style="color: #24292E">;</span></span>
	<span class="line"></span></code></pre>
</div>

If you want to render HTML programmatically. You can do this by resolving the class out of the container, So all the options in the config file can be used.

app(Spatie\LaravelMarkdown\MarkdownRenderer::class)->toHtml($markdown);

Additionally, the MarkdownRenderer can highlight code blocks precisely (via Shiki PHP ) for 100+ languages, including PHP, JS, Blade, and many more. You can add anchor links to headings and, you can cache results to enhance performance.

Its full documentation and source code is available on Github. spatie / laravel-markdown

Written by

Rizwan Aslam

Founder and CEO of CodeBrisk, with years of experience building web applications with Laravel and leading a team of expert developers.

More about Rizwan
Book a free call
Book a call with CodeBrisk