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 - BACKDOORS(2)
Refactoring - Creating a Listener Class #!/usr/bin/env python import socket class Listener: def __in ...
- P3379 最近公共祖先(LCA) 洛谷
题意简单明了(这就是个模板). 就是让我们找2个节点的公共祖先而已,但我们要讲的做法不是生硬的爆搜,而且直接搜好像过不去…… 这次就讲我往后拖了n多天才开始学了倍增LCA. 嗯,这个题,如果2个节点的 ...
- 【C#】根据开始时间和结束时间筛选存在的信息
背景 业务需求中,需要根绝开始时间和结束时间筛选一段时间内的任务存在个数. 示例图片 根据开始时间 9:00到 结束时间11:00 筛选信息 总共有这么四种情况可能出现 插入测试数据 CREATE T ...
- 设计模式:Iterator模式
目的:将数据的存储和数据的查询分开,降低数据的耦合性 继承关系图: 例子: //定义迭代器接口 template<typename T> class Iterator { public: ...
- 05 ES6模块化规范基础详解
ES6模块规范 1.1 ES6规范说明 历史上,JavaScript 一直没有模块(module)体系,无法将一个大程序拆分成互相依赖的小文件,再用简单的方法拼装起来.其他语言都有这项功能,比如 Ru ...
- 带你理解Lock锁原理
同样是锁,先说说synchronized和lock的区别: synchronized是java关键字,是用c++实现的:而lock是用java类,用java可以实现 synchronized可以锁住代 ...
- linux中neovim+tmux安装与配置遇到的问题
Neovim 安装与配置 安装 pip3 install neovim 之前安装过anaconda,默认安装python3和pip3 检查状态 :checkhealth 终端输入'nvim' 进入nv ...
- java大数据最全课程学习笔记(6)--MapReduce精通(二)--MapReduce框架原理
目前CSDN,博客园,简书同步发表中,更多精彩欢迎访问我的gitee pages 目录 MapReduce精通(二) MapReduce框架原理 MapReduce工作流程 InputFormat数据 ...
- 【Laravel】使用 Laravel Excel 实现 Excel/CSV 文件导入导出功能
一.安装配置 使用Composer安装依赖: composer require maatwebsite/excel 发布配置(可选): php artisan vendor:publish --pro ...
- IDEA 修改快捷键和Myeclipse 快捷键一致
介绍 我们知道IDEA这款开发工具功能很强大,为了简化开发步骤,提高开发效率,使用快捷键很显然是必不可少的,那么怎么才能使得IDEA快捷键和MyEclipse快捷键 保持相同呢? 第一种方法,一个快捷 ...