laravellaravel-5commonmark

Unable to render HTML from Markdown


I am going through an online course on Laravel. This course is using the League\commonmark package for converting markdown to html.

Whenever the package is used in the app, I get:

 Unable to find corresponding renderer for block type League\CommonMark\Block\Element\Document 

The app uses the following presenter to do the conversion.

 class PagePresenter extends AbstractPresenter
{
  protected $markdown;

  public function __construct($object, CommonMarkConverter $markdown)
  {
    $this->markdown = $markdown;
    parent::__construct($object);
  }

   public function contentHtml()
   {
    return $this->markdown->convertToHtml($this->content);
   } 
}

Can anyone point me in the right direction?


Solution

  • That happens because the IoC is resolving the dependencies for CommonMarkConverter, specifically Environment which is instantiated with all null properties.

    You can probably resolve this by using a Laravel specific integration: https://github.com/GrahamCampbell/Laravel-Markdown

    Or you can bind and instance to the service container this way:

    In your AppServiceProvider, register method add this:

    $this->app->singleton('Markdown', function ($app) {
    
        // Obtain a pre-configured Environment with all the CommonMark parsers/renderers ready-to-go
        $environment = \League\CommonMark\Environment::createCommonMarkEnvironment();
    
        // Define your configuration:
        $config = ['html_input' => 'escape'];
    
        // Create the converter
        return new \League\CommonMark\CommonMarkConverter($config, $environment);
    });
    

    Now remove CommonMarkConverter from your Presenter constructor add use app('Markdown'):

    class PagePresenter extends AbstractPresenter {
      protected $markdown;
    
      public function __construct($object)
      {
        $this->markdown = app('Markdown');
        parent::__construct($object);
      }
    
       public function contentHtml()
       {
        return $this->markdown->convertToHtml($this->content);
       } 
    }