python - Django 在 Markdown 中包含模板

标签 python django

我有用 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/

相关文章:

python - CNTK & python : How to pass input data to the eval func?

python - 从使用嵌套字典创建的数据帧设置 Pandas 分层多索引

python - 如何在 Django 中添加带有通用外键的 unique_together

django - 如何在Docker Compose中设置 `celeryd`和 `celerybeat`?

python - 执行 Django 单元测试时如何禁用第三方 API?

python - python中的安全身份验证系统?

python - 连续行之间的日期差异 - Pyspark Dataframe

python - 使用 pyinstaller 将 .py 转换为 .exe 后缺少模块

python - django-celery 或 python 的奇怪错误

python - 在 Django 模板中将数字向下舍入到最接近的 1000