我有用 Markdown 编写的 Django 模板。我想实现模板标签以包含渲染的 Markdown 。
{% include_md 'mytemplate.md' }
我编写了模板标签来呈现我的模板:
import markdown
from django.template import Library, loader, Context
@register.simple_tag(takes_context=True)
def include_md(context, template_name):
t = loader.get_template(template_name)
return t.render(Context({
#...
}))
但我需要在函数中间的某个地方放置类似的内容:
markdown.markdown(template_content)
不幸的是,模板加载器不返回模板的内容。那么实现渲染的最佳方式是什么?我不想用 open() 实现我自己的打开模板方法。
最佳答案
Django提供了一个便捷的方法render_to_string
对于这样的情况:
from django.template.loader import render_to_string
@register.simple_tag(takes_context=True)
def include_md(context, template_name):
template = render_to_string(template_name, context)
return markdown.markdown(template)
关于python - Django 在 Markdown 中包含模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60132733/