Django 模板和 Markdown
假设我有一个用 Markdown 编写的 Django 模板。
首先处理 Markdown,然后渲染模板是否有意义,或者我应该渲染模板,然后通过 Markdown 过滤器发送它?
从计算的角度来看,第一个更好,因为我将在循环中渲染模板。我只是想知道是否有一些我没有想到的可能的缺点。
一些参考代码:
import markdown
from django import template
# Here, template_content_md would actually come from the database
template_content_md = """
{{ obj.title }}
-----------
**{{ obj.author }}**
(more Markdown content here using variables)
[More info]({{ obj.get_absolute_url }})
"""
output_list = []
# first method
template_content_html = markdown.markdown(template_content_md)
for obj in object_list:
tt = template.Template(template_content_html)
content_html = tt.render(Context({'obj': obj}))
output_list.append(content_html)
#second method
for obj in object_list:
tt = template.Template(template_content_md)
content_md = tt.render(Context({'obj': obj}))
content_html = markdown.markdown(content_md)
output_list.append(content_html)
如您所见,在第二个版本中,markdown.markdown
为 object_list
中的每个 obj
运行一次。
Suppose I have a Django template written in Markdown.
Does it make sense to process the markdown first, and then render the template, or should I render the template, and then send it through the Markdown filter?
From a computation standpoint the first is preferable, as I'm going to be rendering the template in a loop. I'm just wondering if there are some possible drawbacks I'm not thinking of.
Some code for reference:
import markdown
from django import template
# Here, template_content_md would actually come from the database
template_content_md = """
{{ obj.title }}
-----------
**{{ obj.author }}**
(more Markdown content here using variables)
[More info]({{ obj.get_absolute_url }})
"""
output_list = []
# first method
template_content_html = markdown.markdown(template_content_md)
for obj in object_list:
tt = template.Template(template_content_html)
content_html = tt.render(Context({'obj': obj}))
output_list.append(content_html)
#second method
for obj in object_list:
tt = template.Template(template_content_md)
content_md = tt.render(Context({'obj': obj}))
content_html = markdown.markdown(content_md)
output_list.append(content_html)
As you can see, in the second version, markdown.markdown
is run once for each obj
in object_list
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您从 Markdown 格式的内容生成是一个 Django 模板,因此使用第一种方法最有意义(从 Markdown 模板生成 HTML,然后在循环中使用生成的 Django 模板) 。
除了速度更快之外,这还确保了
obj
中的任何内容都不会被 Markdown 意外翻译成 HTML。我也会“缓存”Django 模板:
Since what you are generating from the Markdown-formatted content is a Django template it makes the most sense to use your first method (generate HTML from the Markdown template and then use the generated Django template in a loop).
As well as being faster, that also ensures that nothing in
obj
is accidentally translated into HTML by Markdown.I would also "cache" the Django template: