首页 > 解决方案 > Django在markdown中包含模板

问题描述

我有用 Markdown 编写的 Django 模板。我想实现模板标签以包含渲染的降价。

{% 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() 实现我自己的打开模板方法。

标签: pythondjango

解决方案


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)

推荐阅读