marked icon indicating copy to clipboard operation
marked copied to clipboard

Catch-all method for Renderer

Open hansy opened this issue 5 years ago • 5 comments

I couldn't find this in the docs, but I was wondering if there was a way to set up some sort of catch-all method for HTML tags that don't match any overwritten renderer methods? For example:

const md = require('marked');
const renderer = new md.Renderer();

renderer.heading = (text, level) => // do something with headings;
renderer.paragraph = text => // do something with paragraphs;

renderer.all = htmlString => // do something with any element not a header or paragraph

md(input, { renderer }, (err, result) => console.log(result);

hansy avatar Sep 15 '18 23:09 hansy

No, any method that is not overwritten is assumed to be using the default implementation

UziTech avatar Sep 16 '18 04:09 UziTech

Perhaps we could add a function that does that. Something like:

const md = require('marked');
const renderer = new md.Renderer();

renderer.all(htmlString => /* set all methods to use this default function */);

// change the methods you want to be different
renderer.heading = (text, level) => // do something with headings;
renderer.paragraph = text => // do something with paragraphs;

md(input, { renderer }, (err, result) => console.log(result);

I would be open to a pull request like that.

UziTech avatar Sep 19 '18 19:09 UziTech

It's pretty easy to achieve today without an additional feature.

const marked = require('marked');
const renderer = new marked.Renderer();

// Do something for all methods
const all = (str) => { console.log('all', str) };

// Magic to wire-up all methods on the renderer
Object.keys(renderer.__proto__).forEach(p => renderer[p] = all);

// Change the methods you want to be different
renderer.heading = (text, level) => { console.log('heading', text, level) }
renderer.paragraph = text => { console.log('paragraph', text) }

marked(input, { renderer }, (err, result) => console.log(result);

styfle avatar Sep 19 '18 20:09 styfle

is this still the best way to implement a catch-all?

marco-silva0000 avatar Jul 15 '20 10:07 marco-silva0000

@marco-silva0000 yes

UziTech avatar Jul 15 '20 20:07 UziTech

Closing as stale. The workaround provided seems sufficient.

UziTech avatar Nov 25 '23 23:11 UziTech