Skip to content

Instantly share code, notes, and snippets.

@bummzack
Created November 6, 2018 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bummzack/d13540d9f37600ccf179a5830f31b97c to your computer and use it in GitHub Desktop.
Save bummzack/d13540d9f37600ccf179a5830f31b97c to your computer and use it in GitHub Desktop.
Markdown textfield
---
Name: markdown-title
---
SilverStripe\Core\Injector\Injector:
Markdown:
class: App\ORM\Markdown
SilverStripe\CMS\Model\SiteTree:
db:
Title: 'Markdown'
MenuTitle: 'Markdown'
<?php
namespace App\ORM;
use Exception;
use Psr\Container\NotFoundExceptionInterface;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\ORM\FieldType\DBVarchar;
class Markdown extends DBVarchar
{
private static $casting = array(
'ToHTML' => 'HTMLText'
);
private static $escape_type = 'xml';
/**
* Render markdown as HTML using Parsedown
*
* @return string Markdown rendered as HTML
*/
public function ToHTML()
{
try {
$parsedown = Injector::inst()->get(\Parsedown::class, true);
// remove the enclosing <p> </p> tags
return substr($parsedown->text($this->value), 3, -4);
} catch (NotFoundExceptionInterface $e) {
} catch (Exception $e) {
}
return '';
}
public function Plain()
{
return strip_tags($this->ToHTML());
}
public function forTemplate()
{
return $this->ToHTML();
}
}
@bummzack
Copy link
Author

bummzack commented Nov 6, 2018

You'd also have to install: https://packagist.org/packages/erusev/parsedown

To improve performance, use partial caching or caching within the class… whatever floats your boat.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment