md文件批量转化为html
任务描述
博客的源文件一般以md文件保存
读取md源文件解析为html代码,然后嵌入到body中去
公式部分,需要使用第三方js库加载
实现办法
基于Django实现,进入webpage页面,然后通过ajax请求服务器,服务器读取md文件并解析为字符串返回到前端,前端使用marked.js库解析为html注入到body中去,其中公式通过MathJax.js来渲染,不过这个会有点慢。
1. 前端代码
<html>
<head>
<script type="text/javascript" src='https://cdn.jsdelivr.net/npm/marked/marked.min.js'></script>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=default"></script>
<script>
$(document).ready(function(){
$.get("/polls/showblog/", function(ret){
$('#content').html(marked(ret["content"]))
});
});
</script>
</head>
<body id="content"> </body>
</html>
2. 后台代码
def webpage(request):
return render(request, 'polls/webpage.html') def showblog(request):
print('current path', os.getcwd())
s = open('blog.md', 'r', encoding='utf8').read()
return HttpResponse(json.dumps({"content": s}, ensure_ascii=False), content_type='application/json')
3. 候选方法
还可以通过后台来将md解析成为html代码,下面是一个网上找的代码
#-*- coding: utf-8 -*
__author__ = 'geebos'
import re
import markdown
from pygments import highlight
from pygments.token import Text, STANDARD_TYPES
from pygments.formatter import Formatter
from pygments.lexers import get_lexer_by_name
from pygments.lexers import guess_lexer def _get_ttype_class(ttype):
fname = STANDARD_TYPES.get(ttype)
if fname:
return fname
aname = ''
while fname is None:
aname = '-' + ttype[-1] + aname
ttype = ttype.parent
fname = STANDARD_TYPES.get(ttype)
return fname + aname def _line_num_tag_gen():
line_num = 0
def result():
nonlocal line_num
line_num += 1
return f'<div class="line-numbers"><div class="line-num" data-line-num="{line_num}"></div></div>'
return result class HtmlLiFormatter(Formatter):
def __init__(self, **options):
Formatter.__init__(self, **options) def _get_css_class(self, ttype):
"""Return the css class of this token type prefixed with
the classprefix option."""
ttypeclass = _get_ttype_class(ttype)
if ttypeclass:
return ttypeclass
return '' def html_encode(self, value):
if '<' in value:
value = value.replace('<', '<')
if '>' in value:
value = value.replace('>', '>')
return value def _get_css_classes(self, ttype):
"""Return the css classes of this token type prefixed with
the classprefix option."""
cls = self._get_css_class(ttype)
while ttype not in STANDARD_TYPES:
ttype = ttype.parent
cls = self._get_css_class(ttype) + ' ' + cls
return cls def format(self, tokensource, outfile):
get_line_num_tag = _line_num_tag_gen()
line_start_tag = '<li class="line">'
line_end_tag = '</li>' code_tags = ['<ol class="code-container">']
num_tags = ['<ol class="num-container">'] line_value = '' outfile.write('<div class="code">') # 预处理
temp_tokensource = []
for ttype, value in tokensource:
value = value.replace(' ', ' ')
if ttype == Text and '\n' in value:
values = re.findall(pattern='([^\n]*)(\n)([^\n]*)', string=value) for i in values:
for k in i:
if k != '':
temp_tokensource.append((ttype, k))
else:
temp_tokensource.append((ttype, value)) for ttype, value in temp_tokensource:
ttype_class = self._get_css_classes(ttype) value = self.html_encode(value) if value != '\n':
line_value += f'<span class="{ttype_class}">{value}</span>'
else:
num_tags.append(get_line_num_tag())
code_tags.append(f'{line_start_tag}<div class="highlight-code"><div class="code-line">{line_value}</div></div>{line_end_tag}\n') line_value = ''
num_tags.append('</ol>')
code_tags.append('</ol>') outfile.write(f'{"".join(num_tags)}{"".join(code_tags)}')
outfile.write('</div>\n') def code_to_html(match):
type_and_content = re.findall(pattern='```(\w*)[\n|\r]([^`]+)```', string=match.group(0))
formatter = HtmlLiFormatter(linenos=True, style='colorful') code_type = type_and_content[0][0]
code_content = type_and_content[0][1] if code_type != '':
substring = highlight(code=code_content, lexer=get_lexer_by_name(code_type), formatter=formatter)
else:
substring = highlight(code=code_content, lexer=guess_lexer(code_content), formatter=formatter) return substring def md_to_html(mdstr):
sub_string = re.sub(pattern='```([^`]+)```', repl=code_to_html, string=mdstr) exts = ['markdown.extensions.extra', 'markdown.extensions.tables'] html = markdown.markdown(sub_string, extensions=exts) return html if __name__ == '__main__':
# 在这里调用md_to_html就可以将md文件内容转化为str类型的html代码
res = md_to_html(open('blog.md', 'r', encoding='utf8').read())
htmlstr = '<html><body>' + res + '</body></html>'
open('webpage.html', 'w', encoding='utf8').write(htmlstr)
结论
博客文件以后用md文件保存就可以了,然后通过md->html->js->注入body的思路,实现批量形成博客网页就可以了。
md文件批量转化为html的更多相关文章
- 用脚本如何实现将Linux下的txt文件批量转化为Windows下的txt文件?
众所周知,Windows和Linux的文件换行回车格式不同,Windows下换行格式是\r\n(回车+换行),Linux下换行格式为\n(只是换行),因此,其中一个操作系统的文本文件若需要在另外一个中 ...
- R语言︱用excel VBA把xlsx批量转化为csv格式
笔者寄语:批量读取目前看到有以下几种方法:xlsx包.RODBC包.批量转化成csv后读入.本章来自博客:http://www.cnblogs.com/weibaar/p/4506144.html 在 ...
- Java实现文件批量重命名
Windows操作系统可以实现重命名文件操作,却不能实现批量重命名.本实例实现了批量重命名功能,可以将一个文件夹内同一类型的文件按照一定的规则批量重命名.用户可以给出重命名模板,程序可以根据模板对相应 ...
- 带进度条的文件批量上传插件uploadify
有时项目中需要一个文件批量上传功能时,个人认为uploadify是快速简便的解决方案. 先上效果图: 一. 下载uploadify 从官网下载uploadify的Flash版本(Flash版本免费,另 ...
- .md文件的语法
md全称是Macdown,.md文件可以当记事本一样使用,作为编辑软件,还可以自己添加样式,图片,链接等,可以用记事本打开,也可以保持样式排版转换为html文件,语法比较简单..md除了编辑容易的优势 ...
- linux 目录下文件批量植入和删除,按日期打包
linux目录下文件批量植入 [root@greymouster http2]# find /usr/local/http2/htdocs/ -type f|xargs sed -i " ...
- Markdown语言.md文件
转自:http://www.kuqin.com/shuoit/20141125/343459.html 之前一直在使用github,也在上面分享了不少的项目和Demo,每次创建新项目的时候,使用的都是 ...
- svn文件批量清除
svn文件批量清除 http://files.cnblogs.com/files/douxuyao/clearsvn.rar
- csv文件批量导入数据到sqlite。
csv文件批量导入数据到sqlite. 代码: f = web.input(bs_switch = {}) # bs_switch 为from表单file字段的namedata =[i.split( ...
随机推荐
- Python Ethical Hacking - MODIFYING DATA IN HTTP LAYER(1)
MODIFYING DATA IN HTTP LAYER Edit requests/responses. Replace download requests. Inject code(html/Ja ...
- 微信小程序入门从这里出发(登录注册、开发工具、文件及结构介绍)
(一) 准备工作 (1) 登录注册 注册账号:这就不谈了,只需要注意使用一个全新的邮箱,别之前注册过公众号小程序等就可以了 https://mp.weixin.qq.com/wxopen/waregi ...
- 面试时谈得很好,为什么就是拿不到offer?
招聘行业有个共识,那就是如果没有给通知一般就是没有通过, 有的学员会问,为什么不打电话通知一下呢? 我猜测,有一方面的原因是怕尴尬,虽然你不觉得尴尬,但是难保有的应聘者会情绪激动,问东问西. 比如你告 ...
- Unable to find a constructor that takes a String param or a valueOf() or fromString() method
Unable to find a constructor that takes a String param or a valueOf() or fromString() method 最近在做服务的 ...
- 0.9循环=lim(n趋于无穷大)(1-1/10的n次方),所以这是一个极限问题
0.9循环=lim(n趋于无穷大)(1-1/10的n次方),所以这是一个极限问题 因为lim(...)(1-1/10的n次方)=1 这意味着维尔斯特拉斯发明极限定义之前,这个等号是不成立的,因为没有极 ...
- PHP操作Redis步骤详解
一.Redis连接与认证 $redis = new Redis(); //连接参数:ip.端口.连接超时时间,连接成功返回true,否则返回false $ret = $redis->connec ...
- Mysql安装使用教程
一:简介 MySQL是一种开放源代码的关系型数据库管理系统(RDBMS),使用最常用的数据库管理语言--结构化查询语言(SQL)进行数据库管理.MySQL是开放源代码的,因此任何人都可以在Genera ...
- Python 图像处理 OpenCV (15):图像轮廓
前文传送门: 「Python 图像处理 OpenCV (1):入门」 「Python 图像处理 OpenCV (2):像素处理与 Numpy 操作以及 Matplotlib 显示图像」 「Python ...
- Python字符串内建函数_上
Python字符串内建函数: 注:汉字属于字符(既是大写又是小写).数字可以是: Unicode 数字,全角数字(双字节),罗马数字,汉字数字. 1.capitalize( ): 将字符串第一个字母大 ...
- markdown利器-小书匠
markdown利器-小书匠 为什么要用markdown语法编写文档? 编写文档的好处这里就不多说了.相信很多人都会在一些博客网站上发布自己的博客,那么怎么能使得自己的博客内容更加具有通用性呢?正如j ...