用Python制作markdown编辑器

还记得在上篇提到的rest-framework,文档中提到了markdown也是可选应用。
那么这篇我们就来尝试使用markdown来制作一个在线的可以预览的editor。

安装 Python Markdown

pip install markdown

使用起来简单地就是两个函数:

  • markdown(text)
  • markdownFromFile(input, output)

具体参见文档:http://pythonhosted.org/Markdown/index.html

markdown(text)会直接把text转换成html格式返回。
我们在应用中就用这个就行了。

首先,在views.py中添加视图:

...
from markdown import markdown

...
def mdeditor(request):
    preview_html = ""
    if request.method == 'POST':
        md_content = request.POST['md_content']
        print("md_content: {}".format(md_content))
        preview_html = markdown(md_content)
    context = {'preview_html':preview_html,}
    return render(request, 'post/mdeditor.html', context)

将从post穿过来的md_content转换成html格式。然后传给post/mdeditor.html这个template返回给浏览器。
所以下一步就是建立一个这样的模板。

<html>
<head><title>markdow editor</title>
<script type="text/javascript">
    function getEditorContent(){
        document.getElementById("md_content").value = document.getElementById("editor").innerHTML;
    }
</script>
</head>
<body>
<div id="editor" style="padding-bottom: 200px" contenteditable="true">

</div>

<form action="mdeditor" method="post" onsubmit="getEditorContent()">
    {% csrf_token %}
    <input type="hidden" id="md_content" name="md_content"/>
    <input  type="submit" />
</form>
{{ preview_html | safe }}<br>

</body>
</html>
  1. 我们使用
    来做编辑器。那么要在表单中返回服务器,就需要将这个值付给一个input标签,就像上面代码做的一样。
  2. 从views.py传过来的preview_html默认会对一些字符进行转义,所以需要添加 | safe

打开浏览起就可以看到效果啦。我们这里使用了python markdown这个应用,可以看到相当的方便。
在上面的代码中,如果使用ajax将内容传回就更好了。但是如果javascript就有markdown的相应的应用就不用传回服务器了,所以如果真要自己使用那么还是找相应的js库方便。

原文地址:https://www.cnblogs.com/wenning/p/5426490.html