Adding Markdown Editor to your Blog/CMS
In this case it is Laravel but any PHP framework could use this.
Get the Library
I used the dflydev-markdown library which uses php-markdown as it’s base. 1
As it notes I load it up with composer.json and I am ready to use it.
Inject the class into your controller
At the controller level I inject it like this
//BaseController.php
use dflydev\markdown\MarkdownExtraParser;
class BaseController {
public $mk;
public function __construct(MarkdownExtraParser $mk = null)
{
$this->mk = ($mk == null) ? new MarkdownExtraParser() : $mk;
}
Later on I call to it on both update and store on any of my Controllers that extend this class.
Add a new field to your Posts or other content type
But the other step here is to add a rendered_body field to my models/tables. Then on store and update I write to these but on edit I am working on the body field which is markdown.
$data['rendered_body'] = $this->mk->transformMarkdown($data['body']);
Render it in the View
And in my Views I render the rendered_body field and NOT the body field which stores the raw text. This idea I got from danneu.com
Now with the help of the docs on php-markdown I can do most of the work I need to make a post, embed video, images etc.
Thoughts
As far as uploading images I use Dropbox for that so it is really not part of my needs. With dropbox I just take a snapshot and it auto uploads the image and I get the url in my clipboard. Though I then have to go to the URL and get the real URL. Still working on that.
{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"repositories": [
{
"type": "git",
"url": "https://github.com/alnutile/dflydev-markdown"
}
],
"require": {
"laravel/framework": "4.1.*",
"dflydev/markdown": "dev-master"
},
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
},
"require-dev": {
"way/generators": "2.*",
"schickling/backup": "dev-master"
},
"scripts": {
"post-install-cmd": [
"php artisan clear-compiled",
"php artisan optimize"
],
"post-update-cmd": [
"php artisan clear-compiled",
"php artisan optimize"
],
"post-create-project-cmd": [
"php artisan key:generate"
]
},
"config": {
"preferred-install": "dist"
},
"minimum-stability": "stable"
}
comments powered by Disqus