1

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?

2

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! – Moucky Aug 21 at 23:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.