Jordan Reiter
Jordan Reiter

Reputation: 21032

Django templates and markdown

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.

Upvotes: 1

Views: 4405

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 160043

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:

template_content_html = markdown.markdown(template_content_md)
# Only generate the template once
tt = template.Template(template_content_html)

for obj in object_list:
    content_html = tt.render(Context({'obj': obj}))
    output_list.append(content_html)

Upvotes: 2

Related Questions