任务描述

博客的源文件一般以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('<', '&lt;')
if '>' in value:
value = value.replace('>', '&gt;')
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(' ', '&nbsp;')
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的更多相关文章

  1. 用脚本如何实现将Linux下的txt文件批量转化为Windows下的txt文件?

    众所周知,Windows和Linux的文件换行回车格式不同,Windows下换行格式是\r\n(回车+换行),Linux下换行格式为\n(只是换行),因此,其中一个操作系统的文本文件若需要在另外一个中 ...

  2. R语言︱用excel VBA把xlsx批量转化为csv格式

    笔者寄语:批量读取目前看到有以下几种方法:xlsx包.RODBC包.批量转化成csv后读入.本章来自博客:http://www.cnblogs.com/weibaar/p/4506144.html 在 ...

  3. Java实现文件批量重命名

    Windows操作系统可以实现重命名文件操作,却不能实现批量重命名.本实例实现了批量重命名功能,可以将一个文件夹内同一类型的文件按照一定的规则批量重命名.用户可以给出重命名模板,程序可以根据模板对相应 ...

  4. 带进度条的文件批量上传插件uploadify

    有时项目中需要一个文件批量上传功能时,个人认为uploadify是快速简便的解决方案. 先上效果图: 一. 下载uploadify 从官网下载uploadify的Flash版本(Flash版本免费,另 ...

  5. .md文件的语法

    md全称是Macdown,.md文件可以当记事本一样使用,作为编辑软件,还可以自己添加样式,图片,链接等,可以用记事本打开,也可以保持样式排版转换为html文件,语法比较简单..md除了编辑容易的优势 ...

  6. linux 目录下文件批量植入和删除,按日期打包

    linux目录下文件批量植入 [root@greymouster http2]# find /usr/local/http2/htdocs/ -type f|xargs sed -i "   ...

  7. Markdown语言.md文件

    转自:http://www.kuqin.com/shuoit/20141125/343459.html 之前一直在使用github,也在上面分享了不少的项目和Demo,每次创建新项目的时候,使用的都是 ...

  8. svn文件批量清除

    svn文件批量清除 http://files.cnblogs.com/files/douxuyao/clearsvn.rar

  9. csv文件批量导入数据到sqlite。

    csv文件批量导入数据到sqlite. 代码: f = web.input(bs_switch = {})  # bs_switch 为from表单file字段的namedata =[i.split( ...

随机推荐

  1. [日常摘要] -- 阻塞IO与非阻塞IO篇

    NIO操作过程 非阻塞读/写操作 读-- 从通道读取数据到buffer,同时可以继续做别的事情,但数据都到buffer之后,线程再继续处理数据 写-- 一个线程请求写入一些数据到某通道,但不需要等待它 ...

  2. 题解 CF613D 【Kingdom and its Cities】

    考虑树形\(DP\),设\(num_x\)记录的为当\(1\)为根时,以\(x\)为子树中重要城市的个数. 那么进行分类讨论: ① 当\(num_x≠0\)时,则需将其所有满足\(num_y≠0\)的 ...

  3. Python 简明教程 --- 25,Python 目录操作

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 做技术一定要一颗恒心,这样才不会半途而废. 目录 上一节我们介绍了文件相关的操作,本节我们来介绍目录 ...

  4. React Navigation / React Native Navigation 多种类型的导航结合使用,构造合理回退栈

    React Navigation 更新到版本5已经是非常完善的一套导航管理组件, 提供了Stack , Tab , Drawer 导航方式 , 那么我们应该怎样设计和组合应用他们来构建一个完美的回退栈 ...

  5. 基于jqgrid + ashx + nhibernate的分页

    因为我目前运维的是一个webform项目,项目中未用到分页的功能,我百度了很多文章也没有一篇是结合jqgrid + ashx + nhibernate的分页,可能是因为后台要请求ashx的原因,不像m ...

  6. java基础(七)--键盘输入

    一.示例 package cnblogs; import java.util.Scanner; public class TestBase07IO { public static void main( ...

  7. python Web项目上线之服务器环境配置

    1.下载安装Xftp 安装成功后,登录服务器用户密码,登录成功后 使用Xftp 将下载好的python解释器linux压缩包放置在服务器根目录下(这里用的是python3.7) 2. 解压压缩包,安装 ...

  8. python处理excel文件(xls和xlsx)

    一.xlrd和xlwt 使用之前需要先安装,windows上如果直接在cmd中运行python则需要先执行pip3 install xlrd和pip3 install xlwt,如果使用pycharm ...

  9. sscanf,sprintf(思修课的收获)

    转载的,就是做个笔记 sprintf函数原型为 int sprintf(char *str, const char *format, ...).作用是格式化字符串,具体功能如下所示: (1)将数字变量 ...

  10. 图解 JVM 核心知识点(面试版)

    一.基本概念 1.1 OpenJDK 自 1996 年 JDK 1.0 发布以来,Sun 公司在大版本上发行了 JDK 1.1.JDK 1.2.JDK 1.3.JDK 1.4.JDK 5,JDK 6 ...