Embed markdown (md) into HTML

2019-04-09 11:07发布

问题:

I need help embedding a markdown, or *.md, file inside of an HTML index file. I have found that I can embed HTML inside of markdown, but not vice-versa. This would help to increase the speed of my editing because markdown format is extremely easy to use, (as I'm using it now) and I don't have to change the format of the rest of my site. I know that something like this is done to embed another HTML file with <iframe src="path/to/html>html-name</iframe>. I could also use javascript to interpret the md format on page load. Thanks ahead of time.

回答1:

Here's the solution that I have long since forgotten about:

Forgetting that I asked this question and getting no answers, I created my own solution as an extension off of Chris Jeffrey's marked.js.

I call it tagdown.js.

Here it is: http://spikespaz.com/tagdownjs/

Just in case that link, or my domain, expires: https://spikespaz.github.io/tagdownjs/

Github: https://github.com/spikespaz/tagdownjs

This allows markdown to be added directly to the site, within a tag set with the class markdown. See the example on the site. There is no theme system in it, it's just the markdown parser.

Update

The project, TagdownJS, has been deleted from Github. The code for it seems so simple that it doesn't deserve its own repository.

Until it finds a new home, just go find Christopher Jeffery's Marked.js, and use this following code with it.

document.body.style.display = "none"; // Hide the page until it's finished rendering.

document.createElement("markdown");
var md_tags = document.getElementsByTagName("markdown"); // Returns array of all markdown tags.

for (var i = 0; i < md_tags.length; i++) { // Iterate through all the tags, and generate the HTML.
    var md_text = md_tags[i].textContent.replace(/^[^\S\n]+/mg, ""); // I love regex, so shoot me.

    var md_div = document.createElement("div"); // Make a new div to replace the fake tag.
    md_div.id = "content";
    md_div.innerHTML = marked(md_text);

    md_tags[i].parentNode.appendChild(md_div); // Add remove the old raw markdown.
    md_tags[i].parentNode.removeChild(md_tags[i]);
}

document.body.style.display = ""; // Show the rendered page.