markdownjavascript-marked

Markdown image URL encoding inconsistency


I have written the following markdown for an image:

![alt-text]({urlVar})

With the intent that the output html is further processed with the url injected through a template system. So, my desired html output is:

<img src="{urlVar}" alt="alt-text" />

You can see in the babelmark3 results that my desired output is the second most common rendering. However, the most common rendering is:

<img src="%7BurlVar%7D" alt="alt-text" />

Which has the curly braces url-encoded. This makes further processing with my template engine not pick up on this template variable.

Is there a way to force the first rendering? Either through standard common-mark / gfm means? Or using the marked javascript library (which I'm using to render)?


Solution

  • It is possible to extend the marked renderer, overriding the built in image renderer. The following script overrides image rendering such that url encoding is not performed and provides a CLI similar to the marked cli.

    import { marked } from 'marked';
    
    // Custom Renderer
    //
    // See: https://marked.js.org/using_pro#renderer
    const renderer = {
      image({href, title, text}) {
        const titleAttr = title ? `title="${title} "` : "";
        return `<img src="${href}" alt="${text}" ${titleAttr}/>`;
      }
    }
    
    marked.use({ renderer });
    
    // You can create own CLI this way.
    //
    // See: https://marked.js.org/using_advanced#cli-extensions
    import 'marked/bin/marked';
    

    if this is saved in scripts/custom-marked.js this script can then be called with node scripts/custom-marked.js -- -s '![alt-text]({urlVar})' and will provide the desired output.

    This relies on: