python - 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() 实现我自己的打开模板方法。
解决方案
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)
推荐阅读
- c# - 带有 systemctl 单元的 net core 5 应用程序不显示带有 journalctl 的日志
- python - 如何使用beautifulsoup 抓取某个表并变成pandas 数据框?
- linux - netstat 缩短/截断主机的 fqdn
- discord.js - 消息嵌入字段值必须是非空字符串
- c++ - 在 C++ 中使用 boost 与可执行文件交互
- flutter - 如何在android视图上单独显示flutter小部件,而不在android视图上显示整个'MyApp'?
- php - Dockerfile:错误:“docker-php-ext-install”不存在且扩展不存在
- c# - 如何为以下 Scenerio 编写 linq 查询
- html - 我想让这个页面响应我该怎么说
- powershell - 使用 PowerShell 脚本创建快捷方式