Fixing Unexpected character "&" in the PyroCMS 3 Markdown Field

Something I have recently gotten into is writing in Markdown - in fact, these very posts in my Guides addon are written in Markdown. It is very readable and great for publishing, but sometimes you want to go further and embed some more complex HTML elements inside it. Markdown natively allows you to do that, but I wanted to supercharge this so I got Twig involved!

The Error

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN)
Method Illuminate\View\View::__toString() must not throw an exception, caught ErrorException: Unexpected character "&".

I ran into this error after I wrote a custom Twig plugin to get an image from its slug, and output a custom bit of HTML for lazy loading and prettier display (Thanks to PyroCMS 3 it is very easy to make a custom Twig plugin!).

The error occured when I rendered the Markdown field in PyroCMS 3 like this:

{% verbatim %}

<div>{{ guide.content.parse()|markdown|raw }}</div>

{% endverbatim %}

The Solution

You should use single quotes instead of double quotes in your Twig plugins inside the PyroCMS Markdown Field!

I discovered this after trying numerous things including escaping, raw output, HTML filters and more, so there you go!

{% verbatim %}

// Do This
{{ guide_image('your-image.jpg')|raw }}
// Don’t Do This
{{ guide_image("your-image.jpg")|raw }}

{% endverbatim %}

This fixed it for me and I have not had any problems since!

References