Marked: Surpress wrapping in <p> tag.

Created on 25 Apr 2014  路  9Comments  路  Source: markedjs/marked

Sometimes I want to write a fragment of markdown and just inject it into template. For example [Email Example](mailto:[email protected]). Marked seems to always wrap it in a <p> tag. Is there an existing way to suppress this behaviour? It makes sense if there is no new line character in the string - like this: marked('[Email Example](mailto:[email protected])'). I've tried different options (gfm, breaks) but they don't seem to affect this.

released

Most helpful comment

Just skip the block-lexing part:

html = marked.inlineLexer(markdown, [], options);

e.g.:

> marked = require('marked');
> marked.inlineLexer('[Email Example](mailto:[email protected])', [])
'<a href="mailto:[email protected]">Email Example</a>'

All 9 comments

Just skip the block-lexing part:

html = marked.inlineLexer(markdown, [], options);

e.g.:

> marked = require('marked');
> marked.inlineLexer('[Email Example](mailto:[email protected])', [])
'<a href="mailto:[email protected]">Email Example</a>'

Excellent. IMHO it would be good to have that in the docs. Maybe it's not that common though.

Can we disable the wrapping of <p>?

Just notice we can disable wrapping with <p> by overriding

Renderer.prototype.paragraph = function(text) {
  return text + '\n';
};

Just noticed we can disable wrapping with <p> by overriding Renderer.prototype.paragraph

@Rugal, Won't that override every single paragraph tag? Or will it just override the initial paragraph wrap?

@radiovisual That will override every single paragraph tag.

Closing as available via advanced usage. If documentation desired, please submit a PR.

Here's what worked for me (many years later). It assumes that you know what elements you don't want to wrap in paragraph tags.

const marked = require("marked");

// Every new line in markdown is considered a new paragraph, this prevents
// img tags from being wrapped in <p> tags which is helpful for resizing img's, 
// centering captions, etc.
marked.Renderer.prototype.paragraph = (text) => {
  if (text.startsWith("<img")) {
    return text + "\n";
  }
  return "<p>" + text + "</p>";
};

html = marked(markdownFile.body)

:tada: This issue has been resolved in version 1.1.2 :tada:

The release is available on:

Your semantic-release bot :package::rocket:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

camwiegert picture camwiegert  路  4Comments

pigtooter picture pigtooter  路  4Comments

gclove picture gclove  路  4Comments

mjbvz picture mjbvz  路  4Comments

toc
zoe-cjf picture zoe-cjf  路  3Comments