编写Markdown模板引擎:让.md文件直接支持Django标签
将Django模板语法嵌入Markdown文件,实现动态内容与纯文本分离,同时保持Markdown的可编辑性。 · 难度:入门 · +10XP
编写Markdown模板引擎
Django默认模板引擎只处理 .html 文件。本教程指导你实现一个自定义引擎,识别 .md 文件,先通过markdown库渲染为HTML,再将结果中的 {{ var }} 和 {% tag %} 交给Django模板引擎二次渲染。支持在Markdown中使用for循环、include其他Markdown片段,以及将Python变量直接注入。最终得到一个适合文档网站、博客系统的混合方案。
from django.template import Engine, Template
import markdown
class MarkdownEngine:
def from_string(self, template_code):
html = markdown.markdown(template_code, extensions=['fenced_code'])
return Template(html)
def get_template(self, template_name):
with open(template_name) as f:
return self.from_string(f.read())