marked.js not rendering image tags

664 views Asked by At

When I have a markdown file with:

![[20230613_110437.jpg]]

in it, and I render it to html with

const html = marked.parse(content);

the html content just contains ![[20230613_110437.jpg]] rather than the image tag.

Also, the image urls should be prefixed with images/, but I don't see a way to configure that.

How do I configure marked to convert this to:

<img src="images/20230613_110437.jpg" />
2

There are 2 answers

0
ufo2mstar On

marked.js does not parse image syntax in Markdown files by default.
To enable this feature, you can use the renderer option to customize the rendering of elements.

Try this configuration to parse image syntax and prefix image URLs with images/:

const marked = require('marked');
const path = require('path');

const renderer = new marked.Renderer();
renderer.image = function(href, title, text) {
  // const url = href.startsWith('http') ? href : `images/${href}`; // for external links
  // return `<img src="${url}" alt="${text}" title="${title}" />`;

  const imagePath = path.join(__dirname, 'images', href);
  return `<img src="${imagePath}" src="${imagePath}" alt="${text}" title="${title}" />`; // for local references
};

const markdown = `![[20230613_110437.jpg]]`;
const html = marked(markdown, { renderer });

console.log(html);
0
Ghost On

I'm not sure if ![[20230613_110437.jpg]] is an actual markdown. Why not just add images in the format of ![]() like:

![image](https://via.placeholder.com/200.png)

That renders to:

image`

marked.use({
    headerIds: false,
    mangle: false,
});

document.getElementById("content").innerHTML = marked.parse(`![image](https://via.placeholder.com/200.png)`);
console.log(marked.parse(`![image](https://via.placeholder.com/200.png)`));
<html>
    <body>
        <div id="content"></div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/5.1.0/marked.min.js"></script>
    </body>
</html>