I'm a little bit stuck using the Element API. I managed to get my JSON file going pretty easily which was great but I've reached a point where I want to include some formatted copy as it would be output using markdown in a .twig template, is this possible?
1 Answer
You can convert your Markdown text to HTML using yii\helpers\Markdown, which is what the |md
Twig filter hooks into:
'transformer' => function(\craft\elements\Entry $entry) {
return [
'body' => \yii\helpers\Markdown::process((string)$entry->yourTextFieldHandle),
];
},
If you want the equivalent of |md('text', inlineOnly=true)
(where only inline elements are parsed – no <p>
tags), call processParagraph()
instead of process()
.
If you want to parse the copy as GitHub Flavored Markdown, pass 'gfm'
as a second argument to process()
:
'transformer' => function(\craft\elements\Entry $entry) {
return [
'body' => \yii\helpers\Markdown::process((string)$entry->yourTextFieldHandle, 'gfm'),
];
},
-
Thanks so much, this worked perfectly. I got something close to this but was looking for helpers within Craft. Didn't think to use Yii helpers. Thanks again!– MouckyCommented Aug 21, 2019 at 23:18