简体   繁体   中英

Converting multiple files into HTML (from Markdown)?

I'm currently working on a small project in which I want to convert couple (or more) Markdown files into HTML and then append them to the main document. I want all this to take place client-side. I have chose couple of plugins such as Showdown (Markdown to HTML converter), jQuery (overall DOM manipulation), and Underscore (for simple templating if necessary). I'm stuck where I can't seem to convert a file into HTML (into a string which has HTML in it).

Converting Markdown into HTML is simple enough:

var converter = new Showdown.converter();
converter.makeHtml('#hello markdown!');

I'm not sure how to fetch (download) a file into the code (string?).

How do I fetch a file from a URL (that URL is a Markdown file), pass it through Showdown and then get a HTML string? I'm only using JavaScript by the way.

You can get an external file and parse it to a string with ajax. The jQuery way is cleaner, but a vanilla JS version might look something like this:

var mdFile = new XMLHttpRequest();
mdFile.open("GET", "http://mypath/myFile.md", true);
mdFile.onreadystatechange = function(){
 // Makes sure the document exists and is ready to parse.
 if (mdFile.readyState === 4 && mdFile.status === 200)   
 {
    var mdText = mdFile.responseText; 
    var converter = new showdown.Converter();
    converter.makeHtml(mdText);
    //Do whatever you want to do with the HTML text
 }
}

jQuery Method:

$.ajax({
  url: "info.md",
  context: document.body,
  success: function(mdText){
    //where text will be the text returned by the ajax call
    var converter = new showdown.Converter();
    var htmlText = converter.makeHtml(mdText);
    $(".outputDiv").append(htmlText); //append this to a div with class outputDiv
  }
});

Note: This assumes the files you want to parse are on your own server. If the files are on the client (IE user files) you'll need to take a different approach

Update

The above methods will work if the files you want are on the same server as you. If they are NOT then you will have to look into CORS if you control the remote server, and a server side solution if you do not. This question provides some relevant background on cross-domain requests.

Once you have the HTML string, you can append to the whatever DOM element you wish, by simply calling:

var myElement = document.getElementById('myElement');
myElement.innerHTML += markdownHTML;

...where markdownHTML is the html gotten back from makeHTML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM