[Answer]-How can I include sub-templates in a dynamically created template?

1👍

If you are willing to waive the requirement that {% include %} statements are needed, you can do things by hand if you try something like this in your view…

def view(request, id):
    theme = get_object_or_404(Theme, pk=id)
    original_context = RequestContext(request)

    page_context = Context({
        'db_head': Template(theme.head_template).render(original_context),
        'db_body': Template(theme.body_template).render(original_context)
    }

    page = Template(theme.page_template)
    return HttpResponse(page.render(page_context))

…With a ‘template’ like this:

<html>
    <head>
        {{ db_head }}
    </head>
    <body>
        {{ db_body }}
    </body>
</html>

This pattern can work for more deeply nested elements as well provided you build the lowest level templates first. You can include existing templates via render_to_string, but you can still run into problems if you ever want to include something within a loop context.

A bit kludgy, and not exactly what you’re looking for, but it will work.

👤NT3RP

Leave a comment