任务描述

博客的源文件一般以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. T3 难题 题解

    小王在考试中遇到一道难题:方程 a1+a2+„„+an=m 的非负整数解有几个,请你帮他算 一下(这也可以算作他作弊吧). 输入格式 一行,两个以空格隔开的数 n,m,表示方程 a1+a2+„„+an ...

  2. T2 监考老师 题解

    第二题,他并不是多难的算法.甚至连搜索都不用,他的题目要求和数据断定了他第二题的地位. 在一个大试场里,有 n 行 m 列的考生,小王和众多同学正在考试,这时,有一部分考生 作弊,当然,监考老师能发现 ...

  3. node.js02 安装Node环境

    安装Node环境 在node.js01中我大概了解了什么是node.js,这次进入起步阶段,首先要安装下Node环境. 开始安装 查看当前Node环境的版本号 win+r输入cmd进入命令行,输入no ...

  4. HashMap源码实现分析

    HashMap源码实现分析 一.前言 HashMap 顾名思义,就是用hash表的原理实现的Map接口容器对象,那什么又是hash表呢. 我们对数组都很熟悉,数组是一个占用连续内存的数据结构,学过C的 ...

  5. vue中使用触摸事件,上滑,下滑,等

    第一步,下载一个包 npm install kim-vue-touch -s 在当前项目中下载包 第二部 import vueTouch from 'kim-vue-touch' Vue.use(vu ...

  6. 洛谷p1120小木棍(剪枝优化)

    #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> ...

  7. python 99乘法表

    先把代码贴上 for i in range(1,10): for j in range(1,i+1): s="%d X %d = %d"%(j,i,i*j) print(s,end ...

  8. 项目管理--PMBOK 读书笔记(4)【项目整合管理】

    项目整合管理:包括对隶属于项目管理过程组的各种过程和项目管理活动进行识别.定义.组合.统一和协调的各个过程. 项目整合管理的核心概念: 1.确保产品.服务或成果的交付日期,项目生命周期以及效益管理计划 ...

  9. Python字符串内建函数_上

    Python字符串内建函数: 注:汉字属于字符(既是大写又是小写).数字可以是: Unicode 数字,全角数字(双字节),罗马数字,汉字数字. 1.capitalize( ): 将字符串第一个字母大 ...

  10. 2020牛客暑期多校训练营 第二场 A All with Pairs 字符串hash KMP

    LINK:All with Pairs 那天下午打这个东西的时候状态极差 推这个东西都推了1个多小时 (比赛是中午考试的我很困 没睡觉直接开肝果然不爽 一开始看错匹配的位置了 以为是\(1-l\)和\ ...