任务描述

博客的源文件一般以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. 01 安装Linux虚拟机

    平常的工作学习中,Linux成为了一项比不可少的需要的掌握的技能,但是大部分人又不习惯于使用Linux进行生活,所以你需要在你的Windows电脑上安装一个虚拟机,那如何安装呢?其实不难,跟着我一步步 ...

  2. Shell基本语法---if语句

    if语句 格式 #单分支 if [ 条件判断 ]; then 执行动作 fi if [ 条件判断 ]; then 执行动作 else 执行动作 fi #多分支 if [条件判断]; then 执行动作 ...

  3. Just test it!!软件测试测起来!!

    (图片: josh@unsplash,字数:700,时间:1分钟) (一) 一切的软件质量保障活动,归根结底,就两种类型. 一种是基于代码执行的,一种是不基于代码执行的. 测试之于肉眼自查.静态检查. ...

  4. 关于Type-C扩展坞干扰路由器交换机的解决方案

    近期看到网友反馈Type-C扩展坞干扰交换机的问题,具体表现为USB Type-C扩展坞在同时插上网线和PD充电的情况下,引起路由器或交换机死机,导致局域网断开的情况.经实测分析,原因为部分电脑默认设 ...

  5. EF批量插入太慢?那是你的姿势不对

    大概所有的程序员应该都接触过批量插入的场景,我也相信任何的程序员都能写出可正常运行的批量插入的代码.但怎样实现一个高效.快速插入的批量插入功能呢? 由于每个人的工作履历,工作年限的不同,在实现这样的一 ...

  6. python关于字符编码的基本操作

    字符编码 (注意:关于字符编码,如果没有特殊业务要求,请牢记仅使用UTF-8编码) 由于Python的字符串类型是str,在内存中以Unicode表示,一个字符对应若干个字节.如果要在网络上传输,或者 ...

  7. Ansible部署zabbix-agent

    playbook目录 zabbix/ ├── hosts ##定义的主机列表 ├── install_zabbix_agent.yml ##安装入口文件 └── roles ├── install_z ...

  8. Lua学习入门(代码块)

    ). if then else if a < then b = else b = end ). if elseif else then if a < then b = elseif a = ...

  9. html中input提示文字样式修改

    在很多网站上我们都看到input输入框显示提示文字,让我们一起来看看如果在input输入框中显示提示文字.我们只需要在<input>标签里添加:placeholder="提示文字 ...

  10. 11-19 configparser模块

    该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值). 创建文件 import configparser config = ...