[Answer]-Insert content in the middle of a Django template variable

1👍

You could accomplish this through a custom template tag. Something like:

from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def render_article(context, article):
    t = template.Template(article.text)
    return t.render(context)

Then in your templates:

{% render_article article %}

Docs about rendering a string as a template are here. Just be very careful about allowing untrusted users to create articles. Someone could put {{ article.__class__.objects.all.delete }} in an article text, causing every article to get deleted when that is rendered.

👤dgel

0👍

There isn’t any built in way to do this. You could implement something yourself, perhaps in the form of a template tag that parses the content with BeautifulSoupv and breaks it up into a list of paragraphs, then assigns that list to a variable you can iterate through.

Leave a comment