How to use spatie’s commonmark-highlighter Laravel package

Highlight.js

spatie/commonmark-highlighter

<?php  
namespace App\Models;

...
use App\Services\CommonMark\CommonMark;
...
class Article extends Model
{
...
public function getFormattedTextAttribute()
{
$body = $this->body;
return CommonMark::convertToHtml($body);
}
...
}
<?phpnamespace App\Services\CommonMark;use League\CommonMark\Block\Element\FencedCode;
use League\CommonMark\Block\Element\IndentedCode;
use League\CommonMark\CommonMarkConverter;
use League\CommonMark\Environment;
use League\CommonMark\Extension\GithubFlavoredMarkdownExtension;
use Spatie\CommonMarkHighlighter\FencedCodeRenderer;
use Spatie\CommonMarkHighlighter\IndentedCodeRenderer;
class CommonMark
{
public static function convertToHtml($markdown)
{
$languages = ['html', 'php', 'js', 'yaml', 'bash', 'xml']; $environment = Environment::createCommonMarkEnvironment();
$environment->addExtension(new GithubFlavoredMarkdownExtension());
$environment->addBlockRenderer(FencedCode::class, new FencedCodeRenderer($languages));
$environment->addBlockRenderer(IndentedCode::class, new IndentedCodeRenderer($languages));
$commonMarkConverter = new CommonMarkConverter([], $environment); return $commonMarkConverter->convertToHtml($markdown); }
}
{!! $article->formatted_text !!}

GitHub

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store