4

Is it possible to access twig filters in a plugin? I want to be able to preview how text will look in a textarea using Markdown for a discussion board, it'd be awesome to use ajax to send the content to the controller then return the filtered version for preview, something like:

public function actionPreviewContentAjax()
{
    $this->requireAjaxRequest();

    $content = craft()->request->getPost('textarea_content');

    // somehow apply twig's "| markdown" filter to $content

    $this->returnJson( $content );
}

Is twig accessible in this manner or am I out of my mind? :X

2 Answers 2

4

In one of your plugin services, you can render a template that handles the markdown filter and return the results as an HTML string. You can then send that HTML to wherever you want to preview.

In your controller:

public function actionPreviewContentAjax()
{
    $this->requireAjaxRequest();

    $content = craft()->request->getPost('textarea_content');

    $html = craft()->pluginName_serviceName->renderMarkdown($content);

    $return = array('html' => $html);

    $this->returnJson( $return );
}

In your service:

public function renderMarkdown($content)
{
    $rendered = craft()->templates->render('path/to/template', array('content' => $content));
    return $rendered;
}

All you would need is a small template that renders your content. If you have this template in your plugin folder, be sure to adjust the template path as described here.

Template:

{{content|markdown}}

If you need more help with the writing services, let me know!

1
  • Worked like a charm. This approach will become handy in lots of other ways too. Many thanks, Aaron!
    – zamo.tox
    Commented Apr 8, 2015 at 18:48
1

This was the only SE question I could find on the topic of parsing Markdown in a plugin, and making a template to run the Markdown filter seems way too roundabout. I found a better solution:

If you're working in Craft 3, Yii/Craft already includes this Markdown parser, which you can use like:

$parser = new \cebe\markdown\Markdown();
$parsedContent = $parser->parse($content);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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