Marked CustomRenderer

https://github.com/chjj/marked

node or browser

Basic

import marked from "marked";

var md = `
# header level 1

* hoge1
* hoge2
* hoge3
`;

var html = marked(md);

console.log(html);
<h1 id="header-level-1">header level 1</h1>
<ul>
<li>hoge1</li>
<li>hoge2</li>
<li>hoge3</li>
</ul>

Custom

import marked from "marked";

class MarkedCustomRenderer extends marked.Renderer {
  heading(text, level) {
    var className = `header-${level}`;
    return `<h${level} class="${className}">${text}</h${level}>`;
  }
}

var md = `
# header level 1

* hoge1
* hoge2
* hoge3
`;

var renderer = new MarkedCustomRenderer();

var html = marked(md, {renderer});

console.log(html);
<h1 class="header-1">header level 1</h1><ul>
<li>hoge1</li>
<li>hoge2</li>
<li>hoge3</li>
</ul>

with Handlebars

import marked from "marked";
import fs from "fs";
import Handlebars from "handlebars";

class MarkedCustomRenderer extends marked.Renderer {
  constructor(opts) {
    this.classes = opts;
  }
  heading(text, level) {
    var classes = this.classes.heading;
    var template = this.loadTemplate("heading");
    var html = template({text, level, classes});
    return html;
  }
  listitem(text) {
    var type = "listitem";
    var classes = this.classes[type];
    var template = this.loadTemplate("listitem");
    var html = template({text,classes});
    return html;
  }
  loadTemplate(type) {
    var filePath = `./template/${type}.hbs`;
    var hbs = fs.readFileSync(filePath, "utf8");
    return Handlebars.compile(hbs);
  }
}

var md = "..";

var classes = {
  "heading"   : ["hogehoge"],
  "listitem"  : ["listitem", "hoge"],
};

var renderer = new MarkedCustomRenderer(classes);
var html = marked(md, {renderer});
console.log(html);
<h{{level}}{{#if classes}} class="{{#each classes}}{{{this}} {{/each}}"{{/if}}>
    {{{text}}}
</h{{level}}>
<li{{#if classes}} class="{{#each classes}}{{this}} {{/each}}"{{/if}}>
    {{{text}}}
</li>

heading.hbs

listitem.hbs

<h1 class="hogehoge ">header level 1</h1>
<ul>
<li class="listitem hoge ">hoge1</li>
<li class="listitem hoge ">hoge2</li>
<li class="listitem hoge ">hoge3</li>
</ul>

very easy!!

Marked Customrenderer

By nakajmg

Marked Customrenderer

Create Markdown renderer using marked & Handlebars.

  • 3,060