markdown to html 终极方案
单独使用且文本内容较多的说明性页面需要做的时候,用markdown写然后用js渲染成html是不错的办法。
较早前已经尝试showdown
,今天在写一个帮助页面时发现不支持表格语法于是搜了下替代的项目,找了下确实有不少选择,换成了 marked.js
。
转换成html还需要找个github风格的css配合使用,这次选的是 github-markdown-css
。
我之前使用的样式是 foundation.min.css
, 现在换用 github-markdown.css
需要把 markdown容器加上 class="markdown-body"
其实两个样式方案都非常的不错,可以看自己的喜好选择。
资源链接见底部,我们先看html代码(其中注释掉的是之前的showdown的用法,也很简单)
<!DOCTYPE html>
<html>
<head lang="en">
<title>帮助文档</title>
<script src="js/jquery.js"></script>
<!--// showdown的代码
<script src="js/showdown.min.js"></script>
-->
<script src="js/marked.min.js"></script>
<!--//
<link rel="stylesheet" href="css/foundation.min.css"/>
-->
<link rel="stylesheet" href="css/github-markdown.css">
</head>
<body>
<div id="container">
<h3> 帮助文档</h3>
<div id="content" class="markdown-body"></div>
</div>
<script>
$(function(){
//加载 doc.md 文件
$.get("doc.md",function(md){
//方案1 showdown
//var sd = new showdown.Converter();
//var html = sd.makeHtml(md);
//方案2 用marked
var html = marked(md);
$("#content").html(html);
});
})
</script>
</body>
</html>
相关链接:
showdown: https://github.com/showdownjs/showdown
markedjs: https://github.com/markedjs/marked
foundation.css: https://cdnjs.cloudflare.com/ajax/libs/foundation/5.5.2/css/foundation.min.css
github-markdown.css: https://github.com/sindresorhus/github-markdown-css
